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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
前提学习:
Java Math的floor,round,ceil函数小结
想法:
3^x=n
log(3^x) = log(n)
x log(3) = log(n)
x = log(n) / log(3)
We need to
largest number power of 3, is 1162261467, we can use this to calculate the float precision. 0.0000000001 at least
Math.log(1162261468)/log(3)
private static final double epsilon = 10e-15;
public boolean isPowerOfThree(int n) {
if (n == 0)
return false;
double res = Math.log(n) / Math.log(3);
return Math.abs(res - Math.round(res)) < epsilon;
}
常规办法(AC过的):
public boolean isPowerOfThree(int n) {
if (n == 0)
return false;
if (n == 1)
return true;
if (n % 3 == 0)
return isPowerOfThree(n / 3);
return false;
}