Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
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
1bit in the binary expression
1bit 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:
Thus it follows that the length of the binary expression is odd.
not num & (num - 1) is to check whether it only has one
len(bin(num)[2:]) & 1) is to check whether the length of the num’s binary expression is odd