leetcode

Power of Four - Link

Question Description

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.


Constraints


Approach

Use 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:

  1. If n is less than or equal to 0, return false (powers of four must be positive)
  2. While n is divisible by 4, divide n by 4
  3. After the loop, if n equals 1, then it was a power of four
  4. Otherwise, it is not a power of four

This approach works because:

Alternative approaches include:


Dry Run

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:


Solution

class Solution {
    public boolean isPowerOfFour(int n) {
        if (n <= 0)
            return false;
        while (n % 4 == 0)
            n = n / 4;
        return n == 1;
    }
}

Time and Space Complexity


Alternative Approaches

Bit Manipulation Approach (More Optimal)

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:

Time Complexity: O(1) - single bitwise operations Space Complexity: O(1) - constant space

Mathematical Approach

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