Power of two


231. Power of Two – LeetCode


Problem Statement

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ˣ


Examples

Example 1:

Input: n = 1
Output: true
Explanation: 2⁰ = 1

Example 2:

Input: n = 16
Output: true
Explanation: 2⁴ = 16

Example 3:

Input: n = 3
Output: false
Explanation: No power of 2 gives 3

Constraints


Intuition

A number is a power of two if and only if it has exactly one 1 bit in its binary representation.

Examples:

This means: if we remove the only set bit, the result should be 0.

Key property:

n & (n - 1) == 0  ⇨  n is a power of 2

Only true when n has exactly one bit set.


Approach: Bit Manipulation

  1. First, check if n is positive (since powers of two are positive).

  2. Use the identity: n & (n - 1) == 0

    • This removes the lowest set bit.

    • If only one bit was set (i.e., power of two), result becomes 0.


Java Code

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

Time and Space Complexity

Metric Value
Time Complexity O(1)
Space Complexity O(1)
Explanation Uses constant-time bitwise operations

Dry Run

Input: n = 16

Input: n = 18


Conclusion

This problem highlights one of the most elegant and efficient uses of bit manipulation: