Power of Three

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?

判断一个整数是否为3的幂。如果一个整数是3的幂,那么就可以表示为
3 ^ x = n  => log(3^x) = log(n) => xlog(3) = log(n) => x = log(n) / log(3)。我们只需要判断x是否为整数就可以了,代码如下:
public class Solution {
    public boolean isPowerOfThree(int n) {
        if(n <= 0) return false;
        double d = Math.log10(n) / Math.log10(3);
        return d % 1 == 0 ? true : false;
    }
}

你可能感兴趣的:(Math)