File: alternating-digit-sum/solution.py

Date: 2026-06-06

Time: 15:14

alternating-digit-sum/solution.py

Purpose

This file solves LeetCode 2544: Alternating Digit Sum. It computes the alternating sum of a positive integer's digits, where the most significant digit gets a positive sign, the next gets negative, and so on. For example, 521+5 - 2 + 1 = 4.

Key Components

sumofdigits(n: int) -> int — The sole function. Takes a positive integer n (1 ≤ n ≤ 10⁹) and returns the alternating digit sum.

The contract is simple: the first (leftmost) digit is always added, the second subtracted, third added, etc.

Flow

1. Convert n to its string representation s, which naturally gives digits in most-significant-first order.

2. Use a generator expression that iterates over enumerate(s), producing (index, digit_char) pairs.

3. For each pair, compute int(d) * (-1) ** i — when i is even the sign is +1, when odd it's -1.

4. sum() accumulates the result.

The (-1) ** i trick is the core idiom: it maps even indices to +1 and odd indices to -1 without branching.

Patterns

Dependencies

Imports: None — pure standard Python.

Imported by: The test_solution.py in the same directory, plus ~350+ test files across other problem directories. The "Imported By" list in the prompt is misleading — those other test files don't actually depend on *this* solution's logic. That list reflects how the test harness resolves imports across the monorepo (likely a shared test runner pattern), not true logical coupling.

Invariants

Error Handling

None. Invalid input (negative numbers, non-integers) will raise exceptions from str()/int() — this is appropriate for a LeetCode solution where input constraints are guaranteed.

Topics to Explore

Beliefs