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.
Subscribe to see which companies asked this question
public class Solution {
public boolean isPowerOfThree(int n) {
if(n == 0) {
return false;
}
if(n == 1) {
return true;
}
while(n % 3 == 0) {
n /= 3;
}
if(n == 1) {
return true;
}
else {
return false;
}
}
}
只写出了用迭代的方法,Google了一下,找到了python版本的写法,要用到Math.log()。但是无奈,Java的标准库中并没有以3为底的log函数。