Show problems as
Classic problem #233HardMathDynamic ProgrammingRecursion

Number of Digit One

Real-world version: Ones Printed Across the Page Numbers
Tracked in this browser only
Read Number of Digit One on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A signwriter numbers pages from 1 up to n, printing each number in ordinary decimal with no leading zeros. When n is 0 nothing is printed at all.

Return how many times the digit 1 is printed across all those page numbers.

Examples

Example 1

Input
n = 25
Output
13

The units place carries a 1 on pages 1, 11 and 21. The tens place carries one on every page from 10 through 19. That is thirteen printed digits.

Example 2

Input
n = 9
Output
1

Among the single-digit pages only page 1 carries the digit.

Example 3

Input
n = 99
Output
20

Ten pages carry a 1 in the tens place and ten pages carry one in the units place, so twenty digits are printed.

Constraints

  • 0 <= n <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def count_digit_one(n: int) -> int:
Java
public int countDigitOne(int n)