oneby7

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: 13

Explanation: 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: 0

Explanation: The only number is 0, and it has no 1s.

Example 3

Input: n = 1000000000000000

Output: 1500000000000001

Check 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.