Power of Two

Easy

Topics
MathBit Manipulation

Given an integer n, return true if it is a power of two (i.e., n == 2^x for some non-negative integer x).

Example 1

76543210n = 100000001n-100000000n & (n-1)00000000
A power of two has exactly one set bit, so n-1 flips every bit below it and n & (n-1) comes out zero. Here it is 0, so the answer is true.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 1
Output: true

Example 2

76543210n = 1600010000n-100001111n & (n-1)00000000
Input:  n = 16
Output: true

Example 3

76543210n = 300000011n-100000010n & (n-1)00000010
Input:  n = 3
Output: false

Constraints

  • -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

A positive power of two has exactly one bit set. Subtracting 1 from such a number flips that bit to 0 and sets every bit below it, so the two values share no bits at all and n & (n - 1) is 0.

n     = 8  = 1000
n - 1 = 7  = 0111
AND        = 0000      exactly one bit was set

n     = 6  = 0110
n - 1 = 5  = 0101
AND        = 0100      more than one bit set

The n > 0 guard is not optional. Zero gives 0 & -1 == 0 and would pass; negatives in two's complement also slip through. So the test is the conjunction.

Approach

  1. Return n > 0 and (n & (n - 1)) == 0.

Dry Run

n = 1   positive, 1 & 0 = 0        -> true
n = 16  positive, 16 & 15 = 0     -> true
n = 3   positive, 3 & 2 = 2       -> false
n = 0   fails the n > 0 guard      -> false
n = -16 fails the n > 0 guard      -> false
        (without it, -16 & -17 == -32, non-zero, so it would
         happen to return false anyway -- but 0 would not)

Complexity

  • Time — O(1): two operations, against O(log n) for repeated division.
  • Space — O(1).

Common Pitfalls

  • Dropping the positivity check, which lets 0 through.
  • Using n % 2 == 0 as the test, which accepts any even number.
  • Using log2(n) and testing for an integer result. Floating point makes large powers land just off, so it is both slower and less reliable.
  • Counting set bits with popcount and comparing to 1. Correct and equally fast, and arguably clearer — but still needs the positivity guard.

Full Solution — all languages

class Solution:
    def isPowerOfTwo(self, n):
        return n > 0 and (n & (n - 1)) == 0
Asked at Qualcomm
SensAI
Beta
Tap the mic to stop voice mode