Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Power of Two Check Implementation in Python

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Power of Two Check runs in O(1) time and O(1) space, in Python as in every other language.
  • ✓CPython has no is_power_of_two builtin. The primitives live on int itself: int.bit_count(), added in Python 3.10, returns the population count, so n.bit_count() == 1 is the direct test, and int.bit_length() gives the number of bits needed, so for a power of two the exponent is n.bit_length() - 1 (e.g.
  • ✓Reviewers want the guard and the test in one expression: n > 0 and n & (n - 1) == 0. In Python & binds tighter than ==, so the extra parentheses that C and Java demand are noise here, and writing ((n & (n - 1)) == 0) reads as translated code.
  • ✓The Python trap: bool subclasses int, so True survives every isinstance(n, int) check and True & (True - 1) == 0 evaluates to True: your validator accepts True as a legal buffer size.
  • ✓Every int is a heap object, so n - 1 allocates a PyLongObject unless the result lands in the -5..256 small-int cache, and n & (n - 1) allocates the AND result too; interpreter dispatch dwarfs the two machine instructions the work actually needs.

What Power of Two Check actually is

A power-of-two test asks whether a positive integer has exactly one bit set: 1, 2, 4, 8, 16, and so on. The standard trick is n > 0 combined with n & (n - 1) == 0, because subtracting one flips the lowest set bit and every bit below it, so the AND clears to zero only when there was a single set bit to begin with. Engineers reach for it when sizing hash tables, ring buffers and allocator blocks, where a power-of-two capacity turns an expensive modulo into a cheap mask (i & (cap - 1)), and when validating an alignment argument before handing it to a lower layer.

Power of Two Check in Python: what you actually reach for

CPython has no is_power_of_two builtin. The primitives live on int itself: int.bit_count(), added in Python 3.10, returns the population count, so n.bit_count() == 1 is the direct test, and int.bit_length() gives the number of bits needed, so for a power of two the exponent is n.bit_length() - 1 (e.g. (8).bit_length() == 4). math.log2 exists but is a float route. Nothing needs importing for the bitwise form n & (n - 1) == 0. For arrays, numpy exposes no power-of-two predicate either; you write (a & (a - 1)) == 0 elementwise over a fixed-width dtype and inherit that dtype's wraparound.

Python implementation

Reviewers want the guard and the test in one expression: n > 0 and n & (n - 1) == 0. In Python & binds tighter than ==, so the extra parentheses that C and Java demand are noise here, and writing ((n & (n - 1)) == 0) reads as translated code. Type-hint the parameter as int, not float. A reviewer will reject math.log2(n).is_integer() and will reject bin(n).count('1') == 1, which allocates a string to stand in for a popcount.
python
def is_power_of_two(n: int) -> bool:
    """True only for 1, 2, 4, 8, ... Rejects bools, zero and negatives."""
    if isinstance(n, bool):          # bool is a subclass of int
        return False
    if not isinstance(n, int) or n <= 0:
        return False
    return n & (n - 1) == 0          # '&' binds tighter than '==' in Python


def is_power_of_two_popcount(n: int) -> bool:
    """int.bit_count() requires Python 3.10 or newer."""
    if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
        return False
    return n.bit_count() == 1


if __name__ == "__main__":
    assert is_power_of_two(1)
    assert is_power_of_two(1 << 200)          # arbitrary precision, still exact
    assert not is_power_of_two(0)
    assert not is_power_of_two(-8)
    assert not is_power_of_two(True)          # the trap this guard closes

    import math
    print(math.log2(2 ** 52 + 1).is_integer())  # True -- and it is a lie
    print(is_power_of_two_popcount(2 ** 52 + 1))  # False -- the bit test is not

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

bool subclasses int, so True survives every isinstance(n, int) check and True & (True - 1) == 0 evaluates to True: your validator accepts True as a legal buffer size. Test isinstance(n, bool) first. The second Python-only twist is the opposite of overflow. Ints are arbitrary precision, so 1 << 10000 is a genuine power of two and the bitwise test still answers correctly, but the float route quietly does not: math.log2(2**52 + 1) rounds to exactly 52.0 on IEEE doubles, so .is_integer() reports a false positive that a machine-word integer path never produces.

Performance in Python, beyond the O(1)

Every int is a heap object, so n - 1 allocates a PyLongObject unless the result lands in the -5..256 small-int cache, and n & (n - 1) allocates the AND result too; interpreter dispatch dwarfs the two machine instructions the work actually needs. n.bit_count() is one method call producing one small int with no intermediate, which is why it wins decisively on large ints, where the AND has to allocate a multi-digit result; for machine-word ints the bitwise form is usually at least as fast, because the method lookup and call cost more than the two specialised binary ops. O(1) is honest only for machine-word-sized values: CPython stores ints in 30-bit digits, so the AND on a 10,000-bit value is linear in digit count. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Power of Two Check between languages.

Real-World Applications

Power of Two Check applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Power of Two Check helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Power of Two Check appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Power of Two Check over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Power of Two Check to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Power of Two Check?

CPython has no is_power_of_two builtin. The primitives live on int itself: int.bit_count(), added in Python 3.10, returns the population count, so n.bit_count() == 1 is the direct test, and int.bit_length() gives the number of bits needed, so for a power of two the exponent is n.bit_length() - 1 (e.g. (8).bit_length() == 4). math.log2 exists but is a float route. Nothing needs importing for the bitwise form n & (n - 1) == 0. For arrays, numpy exposes no power-of-two predicate either; you write (a & (a - 1)) == 0 elementwise over a fixed-width dtype and inherit that dtype's wraparound.

What is the most common Python mistake when implementing Power of Two Check?

bool subclasses int, so True survives every isinstance(n, int) check and True & (True - 1) == 0 evaluates to True: your validator accepts True as a legal buffer size. Test isinstance(n, bool) first. The second Python-only twist is the opposite of overflow. Ints are arbitrary precision, so 1 << 10000 is a genuine power of two and the bitwise test still answers correctly, but the float route quietly does not: math.log2(2**52 + 1) rounds to exactly 52.0 on IEEE doubles, so .is_integer() reports a false positive that a machine-word integer path never produces.

How does Power of Two Check actually perform in Python?

Every int is a heap object, so n - 1 allocates a PyLongObject unless the result lands in the -5..256 small-int cache, and n & (n - 1) allocates the AND result too; interpreter dispatch dwarfs the two machine instructions the work actually needs. n.bit_count() is one method call producing one small int with no intermediate, which is why it wins decisively on large ints, where the AND has to allocate a multi-digit result; for machine-word ints the bitwise form is usually at least as fast, because the method lookup and call cost more than the two specialised binary ops. O(1) is honest only for machine-word-sized values: CPython stores ints in 30-bit digits, so the AND on a 10,000-bit value is linear in digit count. Time complexity is O(1) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Devin offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.