题目描述:
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?
这个题递归法就不写了。
由于这题3的次幂本来就不多,直接枚举都行:
public class Solution {
public boolean isPowerOfThree(int n) {
int[] a={1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441,
1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467};
Set<Integer> set=new HashSet<Integer>();
for(int i=0;i<a.length;i++)
set.add(a[i]);
return set.contains(n);
}
}
如果是这里面的数,肯定能被1162261467整除
public class Solution {
public boolean isPowerOfThree(int n) {
return (n > 0) && (1162261467 % n == 0);
}
}