LeetCode刷题实战342:4的幂
Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.
示例
示例 1:
输入:n = 16
输出:true
示例 2:
输入:n = 5
输出:false
示例 3:
输入:n = 1
输出:true
解题
class Solution {
public:
bool isPowerOfFour(int num) {
if (num == 1){//特殊情况4的零次幂
return true;
}
else if (num == 0 || num % 4 != 0){
//如果不能整除4
return false;
}
else{
return isPowerOfFour(num / 4);
}
}
};
class Solution {
public boolean isPowerOfFour(int num) {
if (num < 0 || (num & (num-1)) > 0 ){
//check(is or not) a power of 2.
return false;
}
if((num & 0x55555555) > 0){
//check 1 on odd bits
return true;
}
return false;
}
}
赞 (0)