Binary Number with Alternating Bits (LeetCode 693): Solution and Explanation
Given a positive integer n, decide whether its binary form alternates, so that no two neighbouring bits are equal. For example 5 (101) alternates and 7 (111) does not.
Intuition
The straightforward check walks the bits from the bottom: look at the lowest bit, shift right, and compare it with the next one. Any equal pair means false. That is at most 31 steps and already fast, but there is a branch-free version that explains the bit structure nicely.
Shifting n right by one moves every bit one column down, so column b of n >> 1 holds bit b + 1 of n, its left neighbour. XOR gives 1 where two bits differ, so x = n ^ (n >> 1) has a 1 in column b exactly when bit b and its left neighbour differ. The top bit of n always compares against a leading 0, so it is 1 too.
That means n alternates if and only if x is a solid run of ones, like 0b11111.
Testing for a run of ones is a classic trick. Adding 1 to 0b11111 carries through every bit and gives 0b100000, which shares no 1 with the original. If x has a 0 anywhere, the carry stops there and the bits above it stay the same in x and x + 1, so the AND is not zero. So x & (x + 1) == 0 is the whole test.
Approach: XOR with the shifted value
- Compute
x = n ^ (n >> 1). Each bit of x says whether that bit of n differs from the bit above it. - n alternates exactly when x is all ones in its low positions.
- Return
(x & (x + 1)) == 0, which is true only for numbers of the form 2^k - 1.
Step-by-step example
n = 5
- n = 101 in binary.
- n >> 1 = 010.
- x = 101 ^ 010 = 111: bit 0 differs from bit 1, bit 1 differs from bit 2, and bit 2 differs from the leading 0.
- x + 1 = 1000.
- x & (x + 1) = 0111 & 1000 = 0, so the function returns true.
Code: Python, Java, C++
1class Solution:
2 def hasAlternatingBits(self, n: int) -> bool:
3 x = n ^ (n >> 1)
4 return x & (x + 1) == 01class Solution {
2 public boolean hasAlternatingBits(int n) {
3 int x = n ^ (n >> 1);
4 return (x & (x + 1)) == 0;
5 }
6}1class Solution {
2public:
3 bool hasAlternatingBits(int n) {
4 unsigned int x = n ^ (n >> 1);
5 return (x & (x + 1)) == 0;
6 }
7};Time and space complexity
O(1)
A shift, an XOR, an addition and an AND, regardless of the value of n.
O(1)
Only the single integer x is stored.
Other approaches
Bit by bit loop (time O(log n), space O(1))
Keep the previous bit, shift n right, and compare each new lowest bit with it. Return false on the first match. Easy to write and easy to reason about.
Binary string check (time O(log n), space O(log n))
Convert n to a binary string and make sure no two adjacent characters are equal, or that the string contains neither "00" nor "11". Readable, but it allocates a string.
Common mistakes
- Checking only that x has no zero bits across all 32 positions. The leading zeros of x are expected, which is why the test uses x + 1 instead of comparing with all ones.
- Signed overflow in C++ when x is 2^31 - 1 (n = 1010...101 with 31 bits). Using an unsigned x avoids undefined behaviour; in Java and C# the wrap-around still gives the right answer.
- Using an arithmetic shift on a negative number. The input is positive here, but the same idea on signed values needs a logical shift.
- Writing
x & x + 1 == 0without parentheses in C-like languages, where == binds tighter than &.
Frequently asked questions
Why is the top bit of x always 1?
The highest 1 bit of n is compared with the 0 above it, so they differ and the XOR is 1 there. That makes x have exactly as many bits as n.
Why does x & (x + 1) == 0 detect a run of ones?
Adding 1 flips the trailing ones to zeros and the first zero to one. If x is all ones, every bit flips and nothing overlaps. If x has a zero somewhere, the bits above that zero are unchanged and overlap.
Is this related to the power of two check?
Yes. x & (x - 1) == 0 tests for a single 1 bit, a power of two. x & (x + 1) == 0 tests the mirror case, a block of ones, which is one less than a power of two.