Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
class Solution {
public:
bool isPowerOfFour(int num) {
if (num&(num-1)) //判断是否为2的幂
{
return false;
}
return num&0x55555555;//判断1是否在奇数位
}
};
0x55555555 十六进制数,是01010101010101010101010101010101,可以用它判断32位二进制数的奇数位上是否为1