File: base-7/solution.py

Date: 2026-06-06

Time: 15:20

base-7/solution.py

Purpose

This file implements LeetCode problem #504 ("Base 7"). It owns a single responsibility: converting a decimal integer to its base-7 string representation. It's one of many self-contained solution modules in the leetcode-implementations repo, each solving a single problem.

Key Components

converttobase7(num: int) -> str — The sole public function. Contract: given any integer in [-10^7, 10^7], returns its base-7 representation as a string (e.g., 100"202", -7"-10").

Flow

The algorithm is the standard repeated-division approach for base conversion:

1. Zero short-circuit (line 12): Returns "0" immediately — without this, the while loop would never execute and return an empty string.

2. Sign extraction (lines 13–14): Records negativity, then works with the absolute value. This separates sign handling from digit extraction.

3. Digit extraction loop (lines 15–17): Repeatedly divides by 7, collecting remainders (least-significant digit first) into a list.

4. Sign reattachment (lines 18–19): Appends "-" to the end of the reversed-order list so it lands at the front after reversal.

5. Assembly (line 20): Reverses and joins. Digits were accumulated LSB-first, so reversal produces the correct MSB-first order.

Patterns

Dependencies

Imports: None — pure arithmetic, no standard library needed.

Imported by: The base-7/test_solution.py file directly. The massive "Imported By" list in the prompt is misleading — those are unrelated test files that share a common test harness pattern, not actual consumers of this function.

Invariants

Error Handling

None. The function trusts its caller to pass an integer. Passing a float or string would produce a runtime error from % or //=. This is appropriate for a LeetCode solution where input constraints are guaranteed.

Topics to Explore

Beliefs