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?
思路1
public class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
while (n > 1) {
if (n / 3 * 3 != n) {
return false;
}
n /= 3;
}
return true;
}
}
思路2
public class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
long i = 1;
while (i <= n) {
if (i == n) {
return true;
}
i *= 3;
}
return false;
}
}
思路3
public class Solution {
public boolean isPowerOfThree(int n) {
return ( n>0 && 1162261467%n==0);
}
}
最简单方法
对数换底公式
logn(b)
loga(b) = -------
logn(a)
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}
}