326. 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?

解决方法:

1、Recursive Solution

public boolean isPowerOfThree(int n) {
    return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));
}

2、Iterative Solution

public boolean isPowerOfThree(int n) {
    if(n>1)
        while(n%3==0) n /= 3;
    return n==1;
}

数学方法

1、找到3的n次方的最大整数,检查是否为输入的整数倍

public boolean isPowerOfThree(int n) {
    int maxPowerOfThree = (int)Math.pow(3, (int)(Math.log(0x7fffffff) / Math.log(3)));
    return n>0 && maxPowerOfThree%n==0;
}

或者更简单一点,3的n次方的最大值maxPowerOfThree = 1162261467。

public boolean isPowerOfThree(int n) {
    return n > 0 && (1162261467 % n == 0);
}

2、log10(n) / log10(3)返回整数

public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}

reference
https://leetcode.com/discuss/78532/summary-all-solutions-new-method-included-at-15-30pm-jan-8th

原文地址:https://www.cnblogs.com/CarryPotMan/p/5343690.html