342. Power of Four
Easy
275128FavoriteShare
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16 Output: true
Example 2:
Input: 5 Output: false
这道题是给一个32位int,判断是否是4的幂。
这道题的解法比判断2的幂多了一个条件(num&0x55555555)!=0
也就是说,先判断是否是2的幂,再把2,8这样的数去掉
来看一看二进制表示下这些数有什么区别:
1 0000 0001
4 0000 0100
16 0001 0000
64 0100 0000 & 0101 0101
2 0000 0010
8 0000 1000
发现奇数位出现单个1是满足要求的,偶数位出现单个1是不满足要求的,因此和5作位与
class Solution {
public:
bool isPowerOfFour(int num) {
//1 0000 0001 (2*2)^n
//4 0000 0100
//16 0001 0000
//64 0100 0000 & 0101 0101
//0x5555 5555
//0001&0101!=0
//0010&0101==0
if(num<=0)return false;
return(((num&(num-1))==0)&&((num&0x55555555)!=0));
}
};