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