Topic description:
Given an integer (32-bit signed integer type), write a function to check if it is a power of 4.
Example:
When num = 16, return true. When num = 5, return false.
Question Advanced: Can you solve this problem without using loops/recursion?
Topic Analysis:
The same idea as the 231 question, or solve this problem through bit operation
First judge the case where the input is 0 and negative
Then analyze the characteristics of powers of 4 0, 4, 16
Convert to binary 0,0100,00010000
The difference from finding the power of 2 is that 2,8 are missing here.
Convert to binary ,0010,00001000
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
4
8
We try to filter out 2,8 using bit operations
Answer code:
C++ version:
class Solution { public: bool isPowerOfFour(int n) { if (n<=0) return false; return ((n&(n-1))==0 && ((n&0x55555555))); } };
Python version:
class Solution: def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num<=0: return False return ((num&(num-1))==0 and (bool(num&0x55555555)))