Check Power of 2 in Python

Beginner
⏱️ 11 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Bits & Binary

What You’ll Learn

Powers of two are numbers like 1, 2, 4, 8, 16… — each is 2^k for some whole k >= 0. In binary they have exactly one set bit. This tutorial covers the classic n & (n - 1) trick, a divide-by-2 loop, a live checker, worked Python examples, edge cases, and complexity.

Definition

2^k

Positive integers of form 2 to a power.

One Set Bit

Binary clue

Exactly one 1 in the binary form.

n & (n-1)

O(1) trick

Zero means power of two (if n > 0).

Divide Loop

No bits

Halve while even; finish at 1.

Live Preview

Try 16 / 6

See binary and the AND result.

Not Just Even

6 fails

Even ≠ power of two.

Introduction

A power of two is a positive integer of the form 2^k. So 16 passes (2^4) while 6 fails even though it is even.

The interview favorite is n > 0 and (n & (n - 1)) == 0. Subtracting 1 from a power of two flips that single set bit and fills lower bits with ones, so AND becomes zero.

Why it matters?

It is a classic bit-trick interview question that connects binary intuition to real systems (buffers, heaps, masks).

Key Highlights

2^k Form

1, 2, 4, 8, 16…

One Set Bit

Binary has a single 1.

n > 0 Guard

Zero and negatives fail.

O(1) Check

Bitwise test is constant time.

In short: positive with exactly one set bit — use n > 0 and (n & (n - 1)) == 0.

📝 Problem & Approach

Given an integer n, decide whether it is a power of two (2^k for some k >= 0).

python
# 16 -> 10000 binary  -> one set bit  -> yes
# 8  -> 1000           -> yes
# 6  -> 110            -> two bits    -> no
# 1  -> 1              -> 2^0         -> yes

Inputs & Outputs

ItemTypeDescription
n / numintValue to test (must be > 0 for yes).
ReturnboolTrue when n is 2^k.
Key expressionbitwise(n & (n - 1)) == 0 with n > 0.

Minimal workflow

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

function is_power_of_two_loop(n):
    if n <= 0:
        return false
    while n > 1 and n mod 2 == 0:
        n = n / 2
    return n == 1

Method comparison

MethodIdeaNotes
n & (n - 1)One set bit clears to zeroInterview favorite — O(1)
Divide by 2Halve while even; end at 1No bitwise syntax needed
bit_count / binCount set bits == 1Readable but usually slower to write

⚡ Quick Reference

GoalPattern
Classic checkn > 0 and (n & (n - 1)) == 0
Alt stylen and not (n & (n - 1))
Reject zeroif n <= 0: return False
Loop checkwhile n > 1 and n % 2 == 0: n //= 2
Loop successreturn n == 1
Interview phrasePositive with exactly one set bit

📋 Bitwise vs Loop vs Even

Same question — different tools and traps.

Bitwise
n & (n - 1)

Fastest interview answer

Divide loop
n //= 2

Great without bitwise ops

Even only
n % 2 == 0

Not enough — 6 fails

8 worked
1000 & 0111

AND is 0 — yes

Context

When This Problem Shows Up

Reach for a power-of-two check whenever sizes or masks must be exact powers.

  1. Bit-trick interviews

    Classic “one set bit” prompt.

  2. Buffer sizes

    Many systems prefer power-of-two lengths.

  3. Heaps and trees

    Capacity and height reasoning.

  4. Mask validation

    Confirm a mask is a single bit.

  5. Not for “even?”

    Use modulo if you only care about parity.

Key benefit: one O(1) expression that proves you understand binary, not just even/odd.

🔮 Live Preview

Uses positive-check plus the bitwise rule, and shows binary for small n.

Enter nonnegative integer values.

Live result
Press “Run check” to see verdict.

Examples Gallery

Three complete Python programs — bitwise check for 16, list powers from 1 to 20, and a divide-by-2 loop without bitwise operators. Click View Output to reveal sample console results.

📚 Getting Started

The classic one-liner interview answer.

Example 1 — Check a Single Number

Fast bitwise check in Python.

python
def is_power_of_two(num: int) -> bool:
    return num > 0 and (num & (num - 1)) == 0


number = 16
if is_power_of_two(number):
    print(f"{number} is a power of 2.")
else:
    print(f"{number} is not a power of 2.")

How It Works

16 in binary is 10000. Then 15 is 01111, so AND is zero. Combined with num > 0, the helper returns True.

⚡ Hunting in a Range

Reuse the helper to list nearby powers of two.

Example 2 — Powers of 2 from 1 to 20

Reuse helper and print all powers in range.

python
def is_power_of_two(num: int) -> bool:
    return num > 0 and (num & (num - 1)) == 0


print("Power of 2 in the range 1 to 20:")
for i in range(1, 21):
    if is_power_of_two(i):
        print(i, end=" ")

How It Works

Within 1..20 the powers are 1, 2, 4, 8, and 16. Numbers like 6, 10, 12, and 14 are even but fail the bit test.

Example 3 — Divide-by-2 Loop (No Bitwise)

Halve while even; finish at 1 means power of two.

python
def is_power_of_two(num: int) -> bool:
    if num <= 0:
        return False
    while num > 1 and num % 2 == 0:
        num //= 2
    return num == 1


for value in (1, 8, 6, 16, 0):
    label = "yes" if is_power_of_two(value) else "no"
    print(f"{value}: {label}")

How It Works

8 becomes 4, then 2, then 1 — success. 6 becomes 3 and stops because 3 is odd and not 1.

🧠 How the Algorithm Decides

1

Require n > 0

Zero and negatives are not powers of two here.

Guard
2

Compute n & (n - 1)

Clears the lowest set bit of n.

Bits
3

Compare to zero

Zero means exactly one set bit was present.

Rule
=

Return the verdict

True for 2^k, else False.

🔎 Worked Walkthrough — 8 vs 6

Compare the bitwise rule on a yes case and a no case.

nBinaryn - 1n & (n - 1)Verdict
8100001110000Yes
16100000111100000Yes
6110101100No
1100Yes (2^0)

One set bit clears to zero under AND; multiple set bits leave leftovers.

Use Cases

Where power-of-two checks show up beyond the interview prompt.

1. Interview Classics

Bit tricks and binary intuition.

Example: is_pow2(16).

2. Capacity Checks

Validate buffer or array sizes.

Example: size must be 2^k.

3. Range Listing

Find powers inside a band.

Example: 1..20 list.

4. Teaching Bits

Show one-set-bit intuition.

Example: 8 vs 6 table.

5. Loop Fallback

Same answer without &.

Example: Example 3.

6. Next: Cube Number

Continue the interview chain.

Example: related CTA.

Pro Tip: open with “positive integer with exactly one set bit” before writing the expression.

Advantages

Why these approaches work well for beginners and interviews.

  1. 1. Constant Time

    The bitwise check is O(1) and tiny.

  2. 2. Binary Intuition

    Forces you to picture set bits clearly.

  3. 3. Loop Fallback

    Same answer without needing & syntax.

  4. 4. Easy Dry Runs

    Trace 8 and 6 on paper in seconds.

Pro Tip: lead with the bit trick; offer the divide loop if the interviewer bans bitwise ops.

Usage Tips

Small habits that keep power-of-two solutions interview-ready.

  1. 1. Guard n > 0

    Never skip the positive check.

  2. 2. Use &, Not and

    Bitwise AND inside; boolean and for the guard.

  3. 3. Dry-Run 8 and 6

    One yes and one no seals understanding.

  4. 4. Keep the Loop Ready

    Useful if bitwise operators are disallowed.

  5. 5. Say the Phrase

    “Exactly one set bit” shows intent.

Pro Tip: sanity-check 1, 16, 6, and 0 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break power-of-two programs.

  1. 1. Accepting Zero

    0 & (-1) can look tricky in languages with wraparound.

    → Require n > 0 explicitly.

  2. 2. Using and Instead of &

    Logical and does not clear bits.

    → Use bitwise & inside the expression.

  3. 3. Thinking Even Is Enough

    6, 10, 12 pass even but fail here.

    → Need exactly one set bit.

  4. 4. Forgetting 1

    1 = 2^0 is a power of two.

    → Include 1 in yes cases.

  5. 5. Accepting Negatives

    This tutorial treats negatives as no.

    → Reject n <= 0.

Edge Cases

Handle these before claiming the check is complete.

n = 1

Yes — 2^0

One set bit still counts.

n = 0

No for this page

n > 0 fails immediately.

n = 6

Even but no

Two set bits in binary.

Negative

Not accepted

Return false here.

& vs and

Bitwise vs logical

Use & inside; and for the guard.

16

Classic yes

10000 & 01111 = 0.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • One set bit. Positive powers of two are exactly the integers with a single 1 in binary.
  • Clear lowest bit. n & (n - 1) clears the least significant set bit of n.
  • Systems habit. Buffer sizes and alignments often prefer powers of two.
  • Not evenness. Power of two is stricter than divisible by two.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 16

  • Show binary 10000
  • AND with 15 is 0

2. Reject 6

  • Binary 110
  • AND leaves a bit

3. List 1..20

  • Reproduce Example 2
  • Expect five values

4. Loop version

  • Implement Example 3
  • Match bitwise results

Notes

  • Definition: power of two means one set bit in a positive integer.
  • Check: use n > 0 and (n & (n - 1)) == 0.
  • Fallback: divide by 2 while even; succeed if you reach 1.
  • Some write num and not (num & (num - 1)). Interview phrase: positive integer with exactly one set bit.

Quick Takeaway: positive with exactly one set bit — n > 0 and (n & (n - 1)) == 0.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Bitwise n & (n - 1)O(1)O(1)
Divide-by-2 loopO(log n)O(1)
Range 1..U scanO(U) checksO(1)

Prefer the bitwise check in interviews unless asked to avoid bit operators.

Wrap Up

🎉 Conclusion

A power of two is a positive integer with exactly one set bit. Use n > 0 and (n & (n - 1)) == 0, or fall back to dividing by 2 until you reach 1.

Practice the three examples above, then continue to checking cube numbers.

One set bit + n > 0 means power of two; even alone is not enough.

💡 Best Practices

✅ Do

  • Require n > 0
  • Use bitwise & for the trick
  • Dry-run 8 and 6
  • Treat 1 as yes (2^0)
  • Keep a divide-loop fallback

❌ Don’t

  • Accept 0 as a power of two
  • Use logical and for bit clearing
  • Confuse with “is even?”
  • Forget negatives fail
  • Skip explaining one set bit

Key Takeaways

Knowledge Unlocked

Five things to remember about powers of two

Decide 2^k the interview-friendly way.

5
Core concepts
& 02

Trick

n & (n-1)

Bitwise
> 03

Guard

n > 0

Edges
/ 04

Loop

halve to 1

Fallback
O 05

Cost

O(1) bits

Analysis

❓ Frequently Asked Questions

A number of form 2^k for whole k >= 0. Examples: 1, 2, 4, 8, 16.
Yes. 1 = 2^0.
For positive powers of two, binary has one set bit. Subtracting 1 clears that bit and sets lower bits, so AND becomes zero.
Zero and negative numbers are not treated as powers of two in this tutorial.
Yes. Repeatedly divide by 2 while even; end at 1 means power of two.
No. Many even numbers like 6 are not powers of two.
No for this page. The guard n > 0 rejects zero.
6 is even but binary 110 has two set bits, so it fails the test.
Positive integer with exactly one set bit.

Did you Know? 🔊

Many computing sizes are powers of two, so this check appears in memory alignment, bit masks, and tree/heap questions.

Continue to Cube Number

Learn how to check whether a number is a perfect cube in Python.

Cube number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful