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?
解法一
循环
public class Solution {
public boolean isPowerOfThree(int n) {
if (n == 0) {
return false;
}
while (n % 3 == 0) {
n = n / 3;
}
return n == 1;
}
}
解法二
log10()方法,如27为3的3次,能整除log10(3)
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}
}
解法三
3^19次方,3^20次方超过最大整数。
public class Solution {
public boolean isPowerOfThree(int n) {
return ( n > 0 && 1162261467 % n == 0);
}
}
解法四
递归
public class Solution {
public boolean isPowerOfThree(int n) {
return (n > 0 && (n == 1 || n % 3 == 0 && isPowerOfThree(n / 3)));
}
}