File: binary-number-with-alternating-bits/solution.py

Date: 2026-06-06

Time: 15:23

binary-number-with-alternating-bits/solution.py

Purpose

Solves LeetCode 693 — Binary Number with Alternating Bits. The file owns exactly one responsibility: determine whether a positive integer's binary representation consists of strictly alternating 0s and 1s (e.g., 5 = 101, 10 = 1010).

Key Components

hasalternatingbits(n: int) -> bool — the sole public function.

Flow

The implementation is a two-step bit-manipulation trick:

1. m = n ^ (n >> 1) — XOR the number with itself shifted right by one. If bits alternate, every pair of adjacent bits differs, so XOR produces an all-ones mask. For example:

2. (m & (m + 1)) == 0 — tests whether m is a sequence of all 1s (i.e., 2^k - 1 for some k). Adding 1 to an all-ones value produces a single 1 followed by all 0s, so the AND is zero. Any 0 bit in m breaks this property.

The entire check runs in O(1) time and O(1) space — no loops, no string conversion, no allocation.

Patterns

Dependencies

Invariants

Error Handling

None. Pure arithmetic — no exceptions, no edge-case guards. Failures would only come from passing a non-integer, which Python's type system doesn't prevent.

Topics to Explore

Beliefs