Digit Count

Source: May 2026, Task 3 (DTU 02002/02003). Study solution — not an official answer key.

Problem

Count how many times digit d (0–9) appears when writing all integers from 1 to N inclusive (e.g. in 11 the digit 1 counts twice).

Write digit_count(N, d).

Example
>>> digit_count(13, 1)
6

Approach

Convert each number to a string and use .count(str(d)), summing over range(1, N+1).

Solution

Show solution Hide solution
Solution
def digit_count(N, d):
    digit = str(d)
    return sum(str(i).count(digit) for i in range(1, N + 1))