Digit Zero Tally

Moderate
0/80
0 upvote

Problem statement

You are given a positive integer N. Your task is to calculate the total number of times the digit '0' appears in the decimal representations of all integers from 1 to N, inclusive.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
A single line containing the integer N.


Output Format:
Print a single integer representing the total count of the digit '0'.


Note:
The problem counts the total occurrences of the digit, not the number of integers that contain the digit. For example, for N=100, the number 10 contributes one '0' and the number 100 contributes two '0's.

A naive approach of iterating from 1 to N and counting zeros in each number as a string would be O(N * log10(N)), which is too slow for the given constraints.

The optimal solution involves a digit-by-digit analysis, often called Digit DP. It calculates the contribution of zeros at each position (units, tens, hundreds, etc.) across the entire range, leading to a much faster O(log10(N)) solution.
Sample Input 1:
20


Sample Output 1:
2


Explanation for Sample 1:
In the range from 1 to 20, the numbers containing the digit '0' are:
- 10 (one '0')
- 20 (one '0')
The total count of '0's is 1 + 1 = 2.


Sample Input 2:
9


Sample Output 2:
0


Explanation for Sample 2:
No numbers from 1 to 9 contain the digit '0'.


Expected Time Complexity:
The expected time complexity is O(log N).


Constraints:
1 <= N <= 10^12

Time limit: 1 sec
Approaches (1)
Dynamic Programming
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Digit Zero Tally
Full screen
Console