The Problem

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 == 2x.

Follow-up: Could you solve it without loops/recursion?

Interactive Visualization

Speed:
Binary Representation
Press Step or Play to begin
Current Step
Press Step or Play to begin.
Code
fun isPowerOfTwo(n: Int): Boolean {    if (n <= 0) {        return false    }    return (n & (n - 1)) == 0 }

How It Works

Key Insight

Powers of two have exactly one bit set in their binary representation. For example: 1 = 20 = 0001, 2 = 21 = 0010, 4 = 22 = 0100, 8 = 23 = 1000. The clever trick is that n - 1 flips all bits after (and including) the rightmost set bit. When we perform n & (n - 1), it clears the lowest set bit. If n is a power of two (exactly one bit), the result is 0. If n has multiple bits set, the result is non-zero.

The Algorithm

  • Step 1: Check if n <= 0. If true, return False (powers of two are positive).
  • Step 2: Compute n - 1, which flips all bits from the rightmost 1 to the right.
  • Step 3: Perform n & (n - 1):
  • โ€” If result is 0: n had exactly one bit set โ†’ return True
  • โ€” If result is non-zero: n had multiple bits set โ†’ return False

Why It Works

For any power of two n = 2k, the binary representation is a single 1 followed by k zeros. Subtracting 1 gives all 1s in the lower k positions. The bitwise AND of these two numbers is always 0:

  • 8 = 1000, 7 = 0111 โ†’ 8 & 7 = 0000 โœ“
  • 16 = 10000, 15 = 01111 โ†’ 16 & 15 = 00000 โœ“

For non-powers of two, there are multiple set bits, so n & (n-1) only clears one bit and leaves others:

  • 6 = 110, 5 = 101 โ†’ 6 & 5 = 100 (non-zero) โœ—
  • 3 = 11, 2 = 10 โ†’ 3 & 2 = 10 (non-zero) โœ—

Complexity

Time O(1)
Space O(1)

The algorithm performs a constant number of operations (one comparison, one subtraction, one bitwise AND, one comparison) regardless of the input size. No additional space is required beyond a few variables.