Description
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?
Solution
Math
利用log
If N is a power of 3:
It follows that 3^X == N
It follows that log (3^X) == log N
It follows that X log 3 == log N
It follows that X == (log N) / (log 3)
For the basis to hold, X must be an integer.
However, due to the fact that log(3) cannot be precisely represented on a binary computer; X is considered an integer if its decimal component falls within a guard range of +/-0.00000000000001. Static imports for log, abs and rint from java.lang.Math.
class Solution {
public boolean isPowerOfThree(int n) {
double a = Math.log(n) / Math.log(3);
return Math.abs(a - Math.rint(a)) <= 0.00000000000001;
}
}
Math
大寫的服!
public boolean isPowerOfThree(int n) {
// 1162261467 is 3^19, 3^20 is bigger than int
return ( n>0 && 1162261467%n==0);
}