mathematics
number theory
powers of two
programming
computational methods

How can I test whether a number is a power of 2?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Checking whether a value is a power of two is a small problem that appears in a surprising number of places: memory allocation, hashing, bit flags, graphics, and low-level optimization. The best solution depends on whether you are working with integers, floating-point values, or user input that first needs validation.

The Fast Integer Test

For positive integers, the standard bit trick is:

python
1def is_power_of_two(n: int) -> bool:
2    return n > 0 and (n & (n - 1)) == 0
3
4for value in [0, 1, 2, 3, 4, 5, 8, 12, 16]:
5    print(value, is_power_of_two(value))

This works because a power of two has exactly one bit set in binary.

  • '1 is 0b1'
  • '2 is 0b10'
  • '4 is 0b100'
  • '8 is 0b1000'

When you subtract 1 from such a number, that single set bit becomes 0 and all lower bits become 1. Performing n & (n - 1) clears the original bit, so the result is 0 only for powers of two.

Examples:

  • '8 is 0b1000'
  • '7 is 0b0111'
  • '8 & 7 is 0b0000'

But for 10:

  • '10 is 0b1010'
  • '9 is 0b1001'
  • '10 & 9 is 0b1000, not 0'

That is why the expression is both fast and widely used.

Why the n > 0 Check Matters

The bit test alone is not enough. 0 & -1 is also 0, so omitting the positive check will incorrectly classify 0 as a power of two.

In some languages, negative numbers create extra confusion because of two's-complement representation. A simple guard avoids those edge cases.

Here is the same logic in Java:

java
1public static boolean isPowerOfTwo(int n) {
2    return n > 0 && (n & (n - 1)) == 0;
3}
4
5public static void main(String[] args) {
6    int[] values = {0, 1, 2, 3, 4, 5, 16, 18};
7    for (int value : values) {
8        System.out.println(value + " -> " + isPowerOfTwo(value));
9    }
10}

If your input type is unsigned, the same idea still applies, but you may not need to worry about negative numbers.

Alternative Approaches

You will also see logarithm-based solutions, such as taking log2(n) and checking whether the result is an integer. That can work for carefully chosen values, but it is usually a worse engineering choice for integer input.

Floating-point math introduces rounding issues. For example, a very large integer may not round-trip cleanly through log2, and a value that should be exact can end up slightly above or below an integer boundary.

A loop is another option:

javascript
1function isPowerOfTwoLoop(n) {
2  if (n < 1) return false;
3  while (n % 2 === 0) {
4    n /= 2;
5  }
6  return n === 1;
7}
8
9console.log(isPowerOfTwoLoop(16));
10console.log(isPowerOfTwoLoop(18));

This is easy to understand and works well for teaching, but it is more verbose than the bitwise version and usually less idiomatic when integers are available.

Choosing the Right Definition

Make sure your definition matches the problem. In most programming contexts, 1 counts as a power of two because 1 = 2^0. If your domain excludes it, document that rule and change the condition accordingly.

Also decide whether your function should accept only integers. If input comes from a form or JSON payload, validate before testing. A string like "16" or a floating-point value like 16.0 may need conversion first.

python
1def parse_and_check(raw: str) -> bool:
2    try:
3        value = int(raw)
4    except ValueError:
5        return False
6    return is_power_of_two(value)

Separating parsing from the actual power-of-two check keeps the core logic clean and easier to test.

Common Pitfalls

The most common bug is forgetting the n > 0 guard. That makes 0 look valid even though it is not a power of two.

Another mistake is using floating-point logs for integer data and then comparing with exact equality. That tends to fail around precision boundaries.

Developers also sometimes apply the bit trick to non-integer values. Bitwise operators are defined on integer representations, so convert the data first and reject values that are not whole numbers.

Finally, be clear about whether 1 should return true. In mathematics and most codebases, it should.

Summary

  • For positive integers, use n > 0 and (n & (n - 1)) == 0.
  • The trick works because powers of two have exactly one set bit.
  • Always guard against 0 and, when relevant, negative inputs.
  • Prefer bitwise checks over logarithms for integer problems.
  • Validate and convert external input before testing it.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.