Coding problem · Easy · Basics

Power of Two

Easy Algorithms & data structures

Return true if n is a power of two: n = 2^k for some integer k >= 0.

Example 1

Input: n = 16
Output: true

Example 2

Input: n = 6
Output: false

Example 3

Input: n = 1
Output: true

Hints

Hint 1

Keep dividing by 2 while the number is even; a power of two ends at 1.

Hint 2

Bit trick: a power of two has exactly one 1 bit, so n & (n − 1) == 0 (for n > 0).

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(log n) · Space O(1)

Divide by 2 while even and check that you end at 1, or use n > 0 && (n & (n - 1)) === 0, which clears the lowest set bit.

Reference solution

function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}

Was this page helpful?