342. Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
// Naive
bool isPowerOfFour(int num) { // time: O(logn); space: O(1)
if (num == 0) return false;
if (num == 1) return true;
int n = num;
while (n > 1) {
if (n % 4 != 0) return false;
n /= 4;
}
return n == 1;
}
// Bit Manipulation
bool isPowerOfFour(int num) { // time: O(1); space: O(1)
// num & (num - 1): remove the last significant digit
// if a number is power of 4, it only has one digit-1
// 0x55555555 is to select out digit-1s in odd positions in binary representation
return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0;
}
Last updated
Was this helpful?