File: number-of-even-and-odd-bits/solution.py

Date: 2026-06-06

Time: 18:18

number-of-even-and-odd-bits/solution.py

Purpose

This file solves LeetCode 2595: Number of Even and Odd Bits. It's one solution module in a large collection (~500+) of LeetCode implementations, each following the same directory convention: {problem-slug}/solution.py.

The single function evenoddindices classifies the set bits (1-bits) in the binary representation of n by whether they sit at even-indexed or odd-indexed positions (0-indexed from the least significant bit).

Key Components

evenoddindices(n: int) -> list[int] — The sole public function. Contract:

Patterns

Bit-walking loop: Rather than converting to a binary string, the code walks the bits from LSB to MSB using n & 1 (extract lowest bit) and n >>= 1 (shift right). A separate counter i tracks the current bit index. This is the idiomatic low-level approach — no string allocation, O(log n) iterations.

Dual accumulator: even and odd are accumulated in a single pass, branching on i % 2. The final return packs them into a two-element list matching LeetCode's expected output format.

Dependencies

Imports: None. The solution is self-contained with no standard library or third-party dependencies.

Imported by: The massive "Imported By" list in the prompt is misleading — those are test files from *other* problems. The actual consumer is number-of-even-and-odd-bits/test_solution.py, which imports this function to run test cases. The other listed files likely share a common test harness pattern that imports from a relative solution module, not from this specific file.

Flow

1. Initialize even = odd = 0 and bit-position counter i = 0.

2. While n is nonzero (has remaining bits):

3. Return [even, odd].

For n = 50 (binary 110010): bit 1 at index 1 (odd), bit 4 at index 4 (even), bit 5 at index 5 (odd) → [1, 2].

Invariants

Error Handling

None. The function trusts its caller to provide a valid positive integer. No validation, no exceptions. This is appropriate for a LeetCode solution where inputs are guaranteed by the judge.

Topics to Explore

Beliefs