Problem 693

Abstract / Summary

Check if every pair of neighboring bits in a number's binary form are different

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
5 lines | 202 bytes | submitted September 10, 2023 | GitHub   60% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (400k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.59 | σ = 0.91

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
42 links | 28 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 2 medium 1 hard
6 solutions   September 10, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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