题目
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
1 | Input: 16 |
Example 2:
1 | Input: 5 |
Follow up: Could you solve it without loops/recursion?
思路
Same as in power of two, we can use bit manipulation to solve this problem.
If num is the power of 4, there is only one
1
bit in the binary expression1
bit must be at the bit standing for the power of 4, i.e. 4, 16, 64. Those bits occur every two bits –> their location is shown below:
10101010101010100
Thus it follows that the length of the binary expression is odd.
not num & (num - 1)
is to check whether it only has one 1
bit;
len(bin(num)[2:]) & 1)
is to check whether the length of the num’s binary expression is odd
代码
1 | class Solution(object): |