Power-of-Two Tricks
Test for powers of two with n & (n-1), isolate the lowest set bit with n & -n, and round up to the next power of two with shift-or smearing.
Overview
A power of two has exactly one 1-bit, so n is a power of two iff n > 0 and n & (n - 1) == 0 — subtracting one clears that lone bit and leaves nothing. Example: 8 = 1000b, 7 = 0111b, 8 & 7 = 0; but 12 & 11 = 1100b & 1011b = 1000b ≠ 0.
n & -n isolates the lowest set bit as a power of two: 12 & -12 = 4. It is the step size of a Fenwick Tree and the key to enumerating set bits. The highest set bit is 1 << floor(log2 n), found by counting leading zeros or by smearing.
Next power of two ≥ n: decrement n, OR it with its own right shifts by 1, 2, 4, 8, 16 (and 32 for 64-bit) so every bit below the top one becomes 1, then add 1. Or in one call: 1 << (bit_length(n - 1)). Related: x & (2^k - 1) is x mod 2^k, (x + 2^k - 1) & ~(2^k - 1) rounds x up to a multiple of 2^k (alignment).
Intuition
A mental model before the formal terms.
A power of two in binary is a single lit bulb in a row of dark ones. Subtracting one "cascades" that bulb: it goes dark and every bulb to its right lights up. Overlay the two rows and nothing coincides — the AND is zero. If there had been a second lit bulb higher up, it would have survived in both rows and shown up in the AND.
Smearing to find the next power of two is like dragging the highest lit bulb rightwards until every bulb below it glows; adding one then carries all the way up into a single new bulb one position higher.
How it works
- Is power of two:
n > 0 && (n & (n - 1)) == 0. - Lowest set bit:
n & -n(two's complement-n = ~n + 1). Its index isctz(n)(count trailing zeros). - Highest set bit:
31 - clz(n)for 32-bitn, orbit_length(n) - 1. The value is1 << that. - Next power of two ≥
n(n ≥ 1):v = n - 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1. - Modulo and division by
2^k:x & (2^k - 1)andx >> k(non-negativex). - Is power of four: power of two and the set bit is in an even position:
(n & 0x55555555) != 0.
Why it works
n - 1 flips the lowest set bit to 0 and all lower zeros to 1, leaving higher bits intact. If n had only one set bit, no higher bits exist and n & (n - 1) has nothing left. If it had two or more, the higher ones survive the AND.
-n = ~n + 1: ~n flips every bit; adding 1 carries through the trailing ones (which were trailing zeros of n) and stops at the first 0 of ~n, which is the lowest 1 of n. Above that, -n is the complement of n, so AND is 0 there; at the lowest set bit both are 1.
Smearing: after v |= v >> 1 the top two bits are set; after >> 2 the top four; the shifts by 1, 2, 4, 8, 16 cover 32 bits in five steps. All bits below the top are now 1, so v + 1 is a single bit above the original top bit — unless n was already a power of two, which the initial n - 1 handles.
Recognition
How to tell a problem wants this.
- "Is
na power of two / four", "round up to a power of two", "align to 8 bytes". - Allocating a hash table or ring buffer whose size must be a power of two so that
index & (size - 1)replacesindex % size. - "Rightmost set bit", "lowest bit", Fenwick tree updates and queries.
Interactive visualization
Play, step, change the input. ← → and space work too.
1isPow2 = n > 0 and (n & (n - 1)) == 02lowest = n & -n3p = n - 14p |= p >> 1; p |= p >> 2; p |= p >> 4 # smear the top bit down5nextPow2 = p + 1Pseudocode
1is_pow2(n) = n > 0 and (n & (n - 1)) == 02lowest_bit(n) = n & -n3highest_bit(n): p = 1; while p * 2 <= n: p *= 2; return p4next_pow2(n):5 v = n - 16 v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 167 return v + 1Implementations
11 · Power-of-two test2def is_power_of_two(n: int) -> bool:3 return n > 0 and (n & (n - 1)) == 04 5 62 · Lowest and highest set bit7def lowest_set_bit(n: int) -> int:8 return n & -n9 10 11def highest_set_bit(n: int) -> int:12 return 1 << (n.bit_length() - 1) if n > 0 else 013 14 153 · Next power of two16def next_power_of_two(n: int) -> int:17 """Smallest power of two >= n. bit_length works for any width."""18 return 1 if n <= 1 else 1 << (n - 1).bit_length()19 20 21def next_power_of_two_smear(n: int) -> int:22 """Same result via smearing, restricted to 32-bit inputs."""23 v = n - 124 v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 1625 return v + 126 27 284 · Power of four and alignment29def is_power_of_four(n: int) -> bool:30 return is_power_of_two(n) and (n.bit_length() - 1) % 2 == 031 32 33def align_up(x: int, k: int) -> int:34 m = (1 << k) - 135 return (x + m) & ~m36 37 38if __name__ == "__main__":39 assert is_power_of_two(64) and not is_power_of_two(12) and not is_power_of_two(0)40 assert lowest_set_bit(12) == 4 and highest_set_bit(12) == 841 assert next_power_of_two(13) == next_power_of_two_smear(13) == 1642 assert next_power_of_two(16) == 1643 assert is_power_of_four(16) and not is_power_of_four(8)44 assert align_up(13, 3) == 16n & (n - 1) == 0with then > 0guard works for any width because Python ints are unbounded.int.bit_length()replaces bothclzand the smear:1 << (bit_length - 1)is the highest set bit and1 << (n - 1).bit_length()the next power of two.- The smear version is included for comparison; its five shifts cover exactly 32 bits.
is_power_of_fourchecks that the single set bit sits at an even index — simpler than a magic mask and width-independent.
O(digits) for enormous ints.
math.log2(n).is_integer()fails for largendue to float rounding; stick to bit tricks.n.bit_length()is exact for every int, including negatives (usesabs).- Python 3.11+ has no
bit_ceil;1 << (n - 1).bit_length()is the one-liner.
- Using floating-point
log2for exact tests. - Applying the 32-bit smear to a number wider than 32 bits and getting a wrong result.
- Omitting the
n > 0guard.
- Highest set bit: C++20
std::bit_floor/std::bit_width(or__builtin_clz, UB for 0); JS/TSMath.clz32(32-bit only); Pythonint.bit_length()for any width. - Next power of two: C++
std::bit_ceil(UB if the result overflows the type); JS must use2 ** kbecause1 << 31is negative; Python1 << (n - 1).bit_length()never overflows. - Range of
n & (n - 1): C++ per type width; JS/TS 31 bits thenBigInt; Python unbounded. - Float
log2tests are unreliable in all four languages for large values; the bit tricks are exact everywhere.
Complexity
Smearing costs a fixed log2(w) steps; clz/ctz-based versions are a single instruction.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- Validating or computing power-of-two sizes for hash tables, ring buffers, segment trees (Segment Tree pads to the next power of two).
- Replacing
%and/by&and>>in hot loops where the divisor is a known power of two. - Fenwick tree traversal and iterating set bits via
n & -n.
- When the divisor is not a power of two — the mask trick is simply wrong, not slow.
- When
nmay be negative or zero and the code does not guard:0 & -1 == 0would wrongly report 0 as a power of two. - In JavaScript for values ≥
2^31— useBigIntorMath.log2on floats.
Alternatives
Common mistakes
- Omitting the
n > 0guard inis_power_of_two. - Skipping the initial
n - 1in next-power-of-two, which returns2nwhennis already a power of two. - Missing the
v |= v >> 32step for 64-bit values (or including it on 32-bit where it is harmless but misleading). - Signed overflow:
nextPowerOfTwo(2^30 + 1)in 32-bit signed arithmetic wraps to a negative number.
Interview patterns
- Power of Two / Power of Four in
O(1)without loops. - Fenwick tree
update/queryloops driven byi & -i. - Bit reversal and "reverse bits" using masks of alternating patterns (
0x55555555,0x33333333,0x0F0F0F0F). - Find the single set bit of
a ^ bto partition two "single numbers" — see XOR Patterns.