Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Power of Two Explained

Problem Statement

Given an integer n, determine whether it is a power of 2, i.e., if there exists a non-negative integer k such that n = 2^k. Powers of 2 have a unique binary representation with exactly one 1 bit (e.g., 8 = 1000). This problem tests your ability to use bitwise operations to check this property efficiently without loops.

Example

Input: n = 16

Output: true

Explanation: 16 = 2^4, so it is a power of 2.

Code

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

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.isPowerOfTwo(16)); // true
    }
}
            
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

# Example usage
print(is_power_of_two(16))  # True
            
function isPowerOfTwo(n) {
    return n > 0 && (n & (n - 1)) === 0;
}

// Example usage
console.log(isPowerOfTwo(16)); // true
            

Explanation

  • Check if n is positive, as negative numbers and zero cannot be powers of 2.
  • Perform the bitwise operation n & (n - 1).
  • For a power of 2, n has exactly one 1 bit (e.g., 16 = 10000).
  • n - 1 has all bits to the right of that 1 set to 1 (e.g., 15 = 01111).
  • ANDing them results in 0 for powers of 2; otherwise, it’s non-zero.

Note

The solution has O(1) time and space complexity, making it highly efficient. This bitwise trick is specific to powers of 2 due to their unique binary structure. Always validate that n is positive to avoid incorrect results.