File: count-the-digits-that-divide-a-number/solution.py

Date: 2026-06-06

Time: 16:05

Purpose

This file solves LeetCode 2520 — Count the Digits That Divide a Number. It owns a single responsibility: given a positive integer, count how many of its decimal digits evenly divide it. The file is self-contained — implementation and tests live together.

Key Components

digitsdividingnum(num: int) -> int

The sole public function. Contract:

TestDigitsDividingNum

Seven unit tests covering:

| Test | Input | Expected | What it validates |

|------|-------|----------|-------------------|

| testsingledigit | 7 | 1 | Base case — one digit always divides itself |

| testrepeateddigit_partial | 121 | 2 | Not all digits need to divide (2 does not divide 121) |

| testalldivide | 1248 | 4 | Every digit divides the number |

| testsingledigit_one | 1 | 1 | Edge: smallest input |

| testlargenumber | 111111111 | 9 | Edge: max digit count (9 ones) |

| testnodigitdividesexcept_one | 13 | 1 | Only digit 1 divides |

| testallsame_digit | 555 | 3 | Repeated digit that divides |

Patterns

Digit extraction via modular arithmetic — the standard n % 10 / n //= 10 loop. This avoids string conversion, keeping the solution in O(d) time and O(1) space where d is the digit count. This is a recurring idiom across this repo's digit-manipulation problems (see self-dividing-numbers, alternating-digit-sum, add-digits).

Collocated tests — the unittest.TestCase subclass lives in the same file as the implementation, with a _main guard. The repo also has separate testsolution.py files that import from these solution modules.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The testsolution.py in this same directory imports from this file. The massive "Imported By" list in the prompt is misleading — those are unrelated test files across the repo that happen to share the same import unittest line, not actual importers of digitsdividing_num.

Flow

1. Save the original num (needed for divisibility checks).

2. Copy num into n as the working variable for digit extraction.

3. Loop: extract the rightmost digit with n % 10, check if num % digit == 0, increment count if so, then drop the digit with n //= 10.

4. The loop terminates when n reaches 0 (all digits consumed).

5. Return the accumulated count.

The digits are processed right-to-left, but order doesn't matter — divisibility is checked against the original number regardless of digit position.

Invariants

Error Handling

None. The function trusts its caller to satisfy the documented precondition (1 <= num <= 10^9, no zero digits). A zero digit would surface as an unhandled ZeroDivisionError from the num % digit expression. This is appropriate for a LeetCode solution where inputs are guaranteed valid.

Topics to Explore

Beliefs