Power of Two

Easymathbit-manipulation
Category: Fundamentals
Companies that ask this question:
AmazonGoogle

Approach

Power of Two

Problem Statement

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

Examples

Example 1:

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

Example 2:

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

Approach

Use bit manipulation: power of 2 has exactly one bit set. Check n > 0 && (n & (n-1)) == 0.

Complexity

  • Time: O(1)
  • Space: O(1)

Solution

java
1class Solution {
2    public boolean isPowerOfTwo(int n) {
3        return n > 0 && (n & (n - 1)) == 0;
4    }
5}
Loading visualizer...