给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x
输入:n = 27 输出:true
打表(预处理)
static Set<Integer> set=new HashSet<>();
static {
int cur=1;
set.add(cur);
while (cur<Integer.MAX_VALUE/3){
cur*=3;
set.add(cur);
}
}
public boolean isPowerOfThree(int n) {
return n>0&&set.contains(n);
}
约数(判断n是不是integer内最大的3次幂的约数)
public boolean isPowerOfThree(int n) {
return n>0&&(int)Math.pow(3,19 )%n==0;
}
遍历取余
public boolean isPowerOfThree(int n) {
if(n<=0){
return false;
}
while (n%3==0){
n/=3;
}
return n==1;
}