Community Problem

Power of Two

Difficulty: Easy

Determine whether a 32-bit signed integer is a power of two using a single bit-AND trick.

Power of Two

Determine whether a 32-bit signed integer is a power of two using a single bit-AND trick.

EASY
Free
bit-manipulation
math

By CodeSnatch

March 9, 2026

·

Updated May 18, 2026

1,141 views

10

4.3 (14)

Asked at a Cloudflare phone screen as the warm-up that decided whether the rest of the loop happened. The interviewer wanted the bit trick, not Math.log2, and was watching for whether I would correctly reject zero and negatives. Easy to state, easy to fail on n = 0 if you trust the formula too much.

Power of Two

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two if there exists an integer x such that n == 2^x.

Examples

Example 1:

  • Input: n = 1
  • Output: true
  • Explanation: 2^0 == 1.

Example 2:

  • Input: n = 16
  • Output: true
  • Explanation: 2^4 == 16.

Example 3:

  • Input: n = 3
  • Output: false
  • Explanation: 3 is not a power of two; its binary form 11 has two set bits.

Example 4:

  • Input: n = 0
  • Output: false
  • Explanation: Zero has no set bits and is not a power of two.

Example 5:

  • Input: n = -16
  • Output: false
  • Explanation: Powers of two are positive by definition for this problem.

Constraints

  • -2^31 <= n <= 2^31 - 1.

Follow-up

Could you solve it without loops or recursion? The bit-AND identity n & (n - 1) == 0 runs in constant time and constant space, no iteration needed.

Solution

Hints

0/3
Hint 1
Hint 2
Hint 3
All Problems