Skip to content

326. Power of Three

Jacky Zhang edited this page Aug 11, 2016 · 1 revision

Given an integer, write a function to determine if it is a power of three.

Follow up:

Could you do it without using any loop / recursion?

##Approach 1: loop

public class Solution {
    public boolean isPowerOfThree(int n) {
        if(n == 0) return false;
        while(n != 1) {
            if(n % 3 != 0) return false;
            n /= 3;
        }
        return true;
    }
}

##Approach 2: without loop 注意到power of 3(除1外)除了1和本身之外,只有因子3。 因此所有能被max power of 3整除的数都是valid power of 3。 3^20已经溢出了,因此最大的数为3^19。

public class Solution {
    public boolean isPowerOfThree(int n) {
        return n > 0 && Math.pow(3,19) % n == 0;
    }
}
Clone this wiki locally