Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4^x.
-2^31 <= n <= 2^31 - 1Use iterative division to check if a number is a power of four. A number n is a power of four if it can be written as 4^x where x ≥ 0.
Algorithm:
n is less than or equal to 0, return false (powers of four must be positive)n is divisible by 4, divide n by 4n equals 1, then it was a power of fourThis approach works because:
Alternative approaches include:
Example 1: n = 16 (4^2)
Step-by-step execution:
Example 2: n = 64 (4^3)
Step-by-step execution:
Example 3: n = 8 (2^3, not power of 4)
Step-by-step execution:
Example 4: n = 5 (not a power of 4)
Step-by-step execution:
Example 5: n = 1 (4^0)
Step-by-step execution:
Example 6: n = 0
Step-by-step execution:
class Solution {
    public boolean isPowerOfFour(int n) {
        if (n <= 0)
            return false;
        while (n % 4 == 0)
            n = n / 4;
        return n == 1;
    }
}
class Solution {
    public boolean isPowerOfFour(int n) {
        // n must be positive power of 2, and when written in binary,
        // should have even number of zeros after the single 1
        return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
    }
}
Explanation:
(n & (n - 1)) == 0 checks if n is power of 20x55555555 is binary 01010101010101010101010101010101(n & 0x55555555) != 0 ensures the single ‘1’ bit is at odd position (1-based)Time Complexity: O(1) - single bitwise operations Space Complexity: O(1) - constant space
class Solution {
    public boolean isPowerOfFour(int n) {
        if (n <= 0) return false;
        double log4 = Math.log(n) / Math.log(4);
        return Math.abs(log4 - Math.round(log4)) < 1e-10;
    }
}
Explanation: Use logarithms to check if n is perfect power of 4.
Time Complexity: O(1) - mathematical operations Space Complexity: O(1) - constant space