All problems

Problem 237

Count Digit One

Hard · 30 pts · Math, Dynamic Programming, Recursion

Problem

You are given an integer N. Count how many times the digit 1 is written in total when you write down every integer from 0 to N. A number like 11 contributes two 1's. N can be up to 10^15, so you cannot write the numbers out. Count digit by digit instead: for each position (ones, tens, hundreds, ...), look at the digits above, at and below that position to work out how many numbers from 0 to N have a 1 there, and add the counts. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).

Input

A single integer N.

Output

Print the count.

Constraints

0 <= N <= 10^15

Example input

13

Example output

6

Explanation

From 0 to 13, the digit 1 appears in 1, 10, 11, 12 and 13. The number 11 has two 1's and the others have one each, so the total is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Euler's Totient Function Next: Convert to Base B