2-D Dynamic Programming Digit DP
605. Number of Digit One
Hard
Given an integer n, write down every whole number from 0 to n, both ends included, in decimal.
Return how many times the digit 1 appears in all of them together.
A number with several 1s counts each of them, so 11 adds 2 and 111 adds 3. The number 0 has no 1s.
Example 1
Input: n = 21
Output:
13Explanation: The 1s come from 1, 10, 11 (two of them), 12, 13, 14, 15, 16, 17, 18, 19 and 21. That is 1 + 1 + 2 + 8 + 1 = 13.
Example 2
Input: n = 0
Output:
0Explanation: The only number is 0, and it has no 1s.
Example 3
Input: n = 1000000000000000
Output:
1500000000000001Check your understanding
Work out the answer for this input before you write any code.
n = 20
Constraints
0 ≤ n ≤ 1015
Clarifying questions
What you would ask an interviewer before writing any code.