Bank app~15 min2s · 256 MBtarget O(log n) time, O(1) spacenumber-theory
A bank app numbers its statements 1, 2, 3 and so on, up to a last number. A label printer prints each statement number on a roll of tape, one character for each digit. The numbers are printed one after another.
Your team lead wants to order enough tape. You must tell how many characters will be printed for all the numbers from 1 to the last one.
Write digits_written(last_number).
last_number, in order, with no leading zeros.Input: last_number = 12
Output: 15The numbers 1 to 9 have one digit each, and 10, 11 and 12 have two digits each.
| Block | Numbers | Digits each | Numbers in the block | Digits |
|---|---|---|---|---|
| 1-digit | 1 to 9 | 1 | 9 | 9 |
| 2-digit | 10 to 12 | 2 | 3 | 6 |
The total is 9 + 6 = 15.
Input: last_number = 9
Output: 9The numbers 1 to 9 have one digit each: 9 digits.
Input: last_number = 1
Output: 1Only the number 1 is printed: 1 digit.
1 ≤ last_number ≤ 10^12Writing every number out costs one step for each number, which is 10^12 steps. No judge finishes that in 2 seconds.
The number 10^12 has 13 digits, so the numbers up to it fall into at most 13 blocks with the same digit count. The total is about 1.2 x 10^13, so it needs a 64-bit number.