Drill

ProblemsJavaScript › patterns

Is it a power of two

easypatternsBit manipulationMathJavaScript

A page allocator only caps sizes at exact powers of two, and a build report flags a size that slipped through.

isPowerOfTwo(amount: int) → bool

Solve it in the editor →

Where you start

function isPowerOfTwo(amount) {
  
}

Worked examples

CallResult
isPowerOfTwo(1)true
isPowerOfTwo(2)true
isPowerOfTwo(4)true
isPowerOfTwo(6)false

Hint

A power of two has exactly one bit set. Clearing the lowest set bit with n & (n - 1) turns it to zero.

Reference solution in JavaScript
function isPowerOfTwo(amount) {
  return amount > 0 && (amount & (amount - 1)) === 0;
}

The same problem in another language

More patterns problems in JavaScript