342. Power of Four
Decription
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?
Solution
- 题意即判断一个数是不是4的次方,且不使用循环。
- 首先,如果一个数是2的次方,那么满足
n & (n - 1) == 0
,因为如果是2的次方,那么肯定满足二进制下最高位是1,其余均是0,而n-1
则是全是1,恰好完成互补。 - 我们注意一个十六进制数
0x55555555
,他是二进制下的1010101010101010101010101010101
,因为一个数如果是4的次方,那么其二进制下的只有奇数位是1,其余均是0,那么可以借用这个特殊的十六进制数完成判断。 - 这就可以在O(1)的时间复杂度下完成判断,代码如下:(注意 == 优先级比 & 高,所以要加括号)
// C++/C
class Solution {
public:
bool isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
}
};
// python
class Solution(object):
def isPowerOfFour(self, num):
return (num > 0) and ((num & (num - 1)) == 0) and ((num & 0x55555555) == num);