方法一:
class Solution {
public boolean isPowerOfFour(int num) {
if(num == 0) return false;
while(num%4 == 0){
num = num>>2;
}
return num ==1;
}
}
方法二:
位运算
4的幂次满足 2进制数只有一个1,1在奇数位上 这个数大于0
class Solution {
public boolean isPowerOfFour(int num) {
return (num>0)&&((num&(num-1)) == 0)&&((num&0x55555555)!=0);
}
}
方法三:
预测法,预先存储4的幂次到哈希表,然后查找
class Powers {
private int n = 15;
public List<Integer> nums = new ArrayList();
Powers() {
int lastNum = 1;
nums.add(lastNum);
for (int i = 1; i < n + 1; ++i) {
lastNum = lastNum * 4;
nums.add(lastNum);
}
}
}
class Solution {
public static Powers p = new Powers();
public boolean isPowerOfFour(int num) {
return p.nums.contains(num);
}
}
方法四:
数学方法