File: sum-of-digits-in-base-k/solution.py

Date: 2026-06-06

Time: 19:21

Purpose

This file solves LeetCode 1837 — Sum of Digits in Base K. It converts a base-10 integer n into its base-k representation and returns the sum of the resulting digits (back in base 10). It's a single-function module — no classes, no imports, no state.

Key Components

sum_base(n: int, k: int) -> int

The sole public function. Contract:

Example: sum_base(34, 6) → 34 in base 6 is 54 (5×6 + 4), so the digit sum is 9.

Patterns

The function uses the standard repeated division idiom for base conversion. Rather than building the full base-k string and then summing characters, it accumulates the digit sum on the fly — each n % k extracts the least-significant digit, and n //= k shifts down. This is the canonical approach: O(log_k(n)) time, O(1) space, no string allocation.

The while n: loop is idiomatic Python for "until n becomes zero." Since n ≥ 1 on entry, the loop always executes at least once.

Dependencies

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

Imported by: The "Imported By" list in the prompt is misleading — those are test files across the entire repo that share a common test harness or conftest, not files that actually call sumbase. The only direct consumer is sum-of-digits-in-base-k/testsolution.py.

Flow


n=34, k=6
─────────────────────────
Iter 1: total += 34 % 6 = 4  → total=4,  n = 34 // 6 = 5
Iter 2: total += 5 % 6  = 5  → total=9,  n = 5 // 6  = 0
Loop ends (n == 0)
Return 9

Data flows linearly: n is consumed destructively (mutated via //=), and total monotonically increases.

Invariants

Error Handling

None. If n=0 is passed, the loop body never executes and the function returns 0 (which happens to be correct). If k=0 or k=1 is passed, the function will raise ZeroDivisionError or loop forever, respectively. These are outside the stated contract.

Topics to Explore

Beliefs