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: trueExample 2:
Input: 5
Output: falseFollow 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;
}Last updated
Was this helpful?