`

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;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics