Skip to the code
cf.
+50 XP

#658 Count a Digit in Page Numbers

hard

A print-preview tool numbers pages from 1 to n. The font file is missing digit d, so the tool warns how many times that digit would be printed across all page numbers.

Write countDigit(n, d) that returns how many times digit d appears when writing every number from 1 to n in decimal, without leading zeros. n can be up to 10^12, so counting number by number is too slow.

Example 1

Input: n = 13, d = 1
Output: 6

The digit 1 appears in 1, 10, 11 (twice), 12, and 13: 6 times.

Example 2

Input: n = 25, d = 2
Output: 9

2, 12, 20, 21, 22 (twice), 23, 24, and 25: 9 times.

Constraints

  • 0 <= n <= 10^12
  • 0 <= d <= 9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).