Checking power of 2 using bitwise operations in JavaScript

We are required to write a JavaScript function that takes in a number and determines whether or not it is a power of two.

For example ?

f(23) = false
f(16) = true
f(1) = true
f(1024) = true

Understanding Powers of Two in Binary

Powers of two in binary form always have exactly one bit set to 1:

1:    0001
2:    0010
4:    0100
8:    1000
16:   10000
32:   100000

The Bitwise Approach

We can use a clever bitwise operation to check if a number is a power of two. For any power of two num, the expression num & (num - 1) will always equal zero.

Why this works:

  • Powers of two have only one bit set
  • Subtracting 1 flips all bits after and including the set bit
  • The AND operation between these two numbers results in zero

Example

const num1 = 256;
const num2 = 1024;
const isPowerOfTwo = (num = 1) => {
    if (num 

true
true
true
false

How the Bitwise Operation Works

Let's trace through the bitwise logic for number 8:

8 in binary:     1000
8 - 1 = 7:       0111
8 & 7:           0000 (result is 0, so 8 is power of 2)

For 6 (not a power of 2):
6 in binary:     0110
6 - 1 = 5:       0101
6 & 5:           0100 (result is not 0, so 6 is not power of 2)

Complete Solution with Edge Cases

function isPowerOfTwo(num) {
    // Check for positive numbers only
    if (num 

true
true
true
false
false
false

Key Points

  • The bitwise approach (num & (num - 1)) === 0 is the most efficient method
  • Time complexity: O(1) - constant time
  • Space complexity: O(1) - no extra space needed
  • Always check that the number is positive before applying the bitwise operation

Conclusion

Using bitwise operations to check powers of two is an elegant and efficient solution. The key insight is that powers of two have exactly one bit set, making num & (num - 1) always equal zero for valid powers of two.

Updated on: 2026-03-15T23:19:00+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements