题目:
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?
Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases.
解析:
使用二进制来考虑问题。
因为是32位有符号数,所以先保证num > 0。一个数是4的幂必然是2的幂,先来看看2的幂的特征(num & (num - 1)) == 0
比如数字8:(8 & 7) --> (0x1000 & 0x0111)。所有是2的幂的数n都满足二进制位只有一个1,后面都是0。(n-1)满足全为1。
再在2的幂中筛选去掉不是4的幂的。
4的幂的二进制中1总是出现在奇数位,比如:4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000)
其他则是在偶数位,比如 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)
所以要满足(num & 0x55555555) != 0
,这里0x55555555
(0b 0101 0101 0101 0101 0101 0101 0101 0101
)正是32位有符号整数。
答案一:
class Solution {
public:
bool isPowerOfFour(int num) {
return ((num > 0)
&& ((num & (num - 1)) == 0)
&& ((num & 0x55555555) == num) );
}
};
答案二(基础解法):
class Solution {
public:
bool isPowerOfFour(int num) {
if (num == 1) {
return true;
}
if (num == 0) {
return false;
}
while ( (num % 4 == 0)) {
num /= 4;
if (num == 1) {
return true;
}
}
return false;
}
};