Python 0693.py
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n ^= n >> 1 # now all bits set
n += 1 # now power of two
return (n & (n - 1)) == 0 # clear lowest bit
Difficulty
and has an acceptance rate of about 70% (400k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether the binary representation of a non-negative integer consists of alternating 0s and 1s. It does so by applying a series of bitwise transformations that collapse the alternating pattern into a simple property of powers of two. The logic is compact, relies solely on integer arithmetic, and executes in constant time for any input size supported by the language’s integer type.
Key Steps
The algorithm proceeds through three distinct operations, each expressed as a single line of code.
n ^= n >> 1
The first line XORs the original number with a version shifted right by one position. In an alternating bit pattern, each pair of adjacent bits differs, so the XOR produces a sequence of 1s covering the entire length of the original representation. For a number that does not alternate, the result will contain at least one 0 among the 1s.
n += 1
Adding one to a binary string composed entirely of 1s yields a value that is a power of two: a single 1 followed by zeros. If the previous step left any 0 in the pattern, the addition will not produce a clean power-of-two form.
return (n & (n - 1)) == 0
The final expression checks whether the current value is a power of two. The well-known property that a power of two has exactly one bit set means that performing a bitwise AND between the number and its predecessor clears all bits, resulting in zero. The boolean result of this comparison is returned directly.
Edge Cases Handled
The code gracefully handles the smallest inputs, including zero and one. For n = 0, the shift yields zero, the XOR leaves zero unchanged, the addition produces one, and the final check confirms that one is a power of two, returning True. This matches the definition that a single-bit representation (or an empty pattern) satisfies the alternating condition. For n = 1, the XOR produces zero, the addition yields one, and the power-of-two test again succeeds, returning True.
When the input contains leading zeros in its binary representation, those zeros are not represented in the integer value, so the algorithm implicitly works with the minimal-length representation. Any integer that contains a pair of identical adjacent bits-such as 3 (11) or 5 (101)-fails the XOR-then-add test because the XOR result will contain a zero, and the subsequent addition will not generate a pure power of two. Consequently, the final check evaluates to False.
The method also accommodates the maximum integer size supported by the runtime. Since all operations are bitwise and arithmetic on a single word, overflow does not occur in Python’s arbitrary-precision integer model; the algorithm remains correct for arbitrarily large inputs.
Performance Optimizations
The implementation achieves optimal performance by limiting itself to three primitive operations: a right shift, an XOR, an addition, and a single AND-comparison. Each operation runs in hardware-level time for fixed-size integers, and Python’s internal handling of big integers still executes these steps in linear time relative to the number of machine words, which is negligible for typical problem constraints.
By collapsing the alternating-bit property into a power-of-two test, the code avoids any loops, recursion, or string conversions that would introduce additional overhead. The use of a direct boolean expression as the return value eliminates the need for an explicit conditional branch, allowing the interpreter to produce a concise bytecode sequence. This design yields a highly efficient solution that scales uniformly across all valid inputs.
ELI5 - Simplified Explanation
Imagine that the computer is a big box filled with tiny light switches that can only be either on or off. Each switch is a bit. Sometimes these switches follow a perfect pattern where they go on, off, on, off, and so on. This code is like a little checker that looks at a number to see if its switches are dancing in that perfect rhythm.
First, the code does a clever trick by taking the current pattern and mixing it with a copy of itself shifted over. If the switches were already in a perfect alternating pattern, this mix makes all the switches suddenly turn on into a solid row.
Next, it adds one tiny bit to that row. When you add one to a row of switches that are all turned on, it turns into a single switch at the very end followed by a bunch of switches that are all turned off. This is a special power of two.
Finally, the code does one last bit of magic to see if that power of two is clean and tidy. It checks if the number is exactly what it should be if it really followed that perfect alternating rhythm all the way through. It is a very fast way for the computer to finish its dance check.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C# | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C# | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 191: Number of 1 Bits
Solved On The Same Day
- problem 661: Image Smoother
- problem 762: Prime Number of Set Bits in Binary Representation
- problem 319: Bulb Switcher
- problem 2336: Smallest Number in Infinite Set
- problem 679: 24 Game
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality