Article start
DSA Course: Interview Patterns and Problem Solving
Module 14: Bit Manipulation

Power of Two: n and n-1 Pattern

Check whether a positive number has exactly one set bit.

May 29, 2026·24

Learning Outcome

After this lesson, you should be able to recognize the one-set-bit property of powers of two.

Problem Statement

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

InputOutputWhy
n = 16true16 is binary 10000, which has exactly one set bit.

Brute Force Approach

Repeatedly divide by 2 until the number becomes odd. This works but is longer and easy to mishandle for zero or negative values.

Optimized Approach

A positive power of two has one set bit. n & (n

    1. clears the lowest set bit, so the result is zero only when there was one set bit.

Exact Pseudocode

if n <= 0:
  return false
return (n & (n - 1)) == 0

Reference Code

class Solution:
    def isPowerOfTwo(self, n):
        return n > 0 and (n & (n - 1)) == 0

Sample Dry Run

StepStateResult
n = 16binary 10000one set bit

n

  • 1 = 15
binary 01111lower bits become 1

n & (n

10000 & 01111 = 00000true
n = 1810010 & 10001 is not zerofalse

Complexity

MeasureValueReason
TimeO(1)The check uses constant-time bit operations.
SpaceO(1)No extra data structure is used.

Edge Cases

  • Zero is not a power of two.
  • Negative numbers are not powers of two.
  • Do the n > 0 check before trusting the bit expression.

Interview Checklist

  • Remember the one-set-bit property.
  • Use n & (n

      1. to remove the lowest set bit.
  • Guard against n <= 0.

FAQs

Why does zero need a separate check?

0 & -1 is 0, so without n > 0, zero would incorrectly pass.

What does n & (n

    1. do?

It clears the lowest set bit of n.

What is the core pattern?

Single-set-bit check.

Test your knowledge

Take a quick quiz based on this chapter.

mediumDSA Course
Power of Two - n and n-1 Pattern Practice Quiz
5 questions8 min

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.