leetcode

Power of Two - Link

Question Description

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2^x.


Constraints


Approach

Use iterative division to check if a number is a power of two. A number n is a power of two if it can be written as 2^k where k ≥ 0.

Algorithm:

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

This approach works because:

Alternative approaches include:


Dry Run

Example 1: n = 16

Step-by-step execution:

Example 2: n = 12

Step-by-step execution:

Example 3: n = 1

Step-by-step execution:

Example 4: n = 0

Step-by-step execution:


Solution

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

Time and Space Complexity


Alternative Approaches

Bit Manipulation Approach

class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}

Explanation: Powers of two have exactly one ‘1’ bit in binary. Using n & (n - 1) clears the least significant ‘1’ bit. If result is 0 and n > 0, then n is a power of two.

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