Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Power of Two

Bit Manipulationeasy

Implement `isPowerOfTwo(n)` returning whether the integer `n` is a power of two.

Sample tests

Input: isPowerOfTwo(1)
Output: true
Input: isPowerOfTwo(16)
Output: true

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting that zero and negatives are not powers of two.

Learning resources

  • MDN: Bitwise operators
Approach & explanation (try first)

n > 0 and n & (n-1) === 0 detects a single set bit in O(1) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.