Check Power of Two

Ishank Sharma
1 min readMar 3, 2021

Given an integer n greater than or equal to 0, return whether it is a power of two.

Constraints

  • 0 ≤ n < 2 ** 31

Example 1

Input

n = 0

Output

false

Intuition

Binary numbers of 2’s power are of form 10000000. and subtracting a value 1 less than it will give us 01111111111.
So if we bit mask it we can find whether a binary number is of this form or not doing an & op will res in zero.

Implementation

If the number is zero return false;
If the number is one return true;
Mask with a number 1 less than the input;
if the result is zero we have a 2nth power number else not.

Time Complexity

O(1) it will only run for one iteration

Space Complexity

O(1) only requires constant space operation

Code

class Solution {
solve(n) {
if (n === 0) return false;
if (n === 1) return true;
if ((n & (n - 1)) === 0)
return true;
else return false;
}
}

--

--