Number of Digit One - Problem

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example, if n = 13, the numbers are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. The digit 1 appears in: 1, 10, 11, 12, 13. Counting each occurrence: 1 appears 1 time, 10 has 1 occurrence, 11 has 2 occurrences, 12 has 1 occurrence, and 13 has 1 occurrence. Total = 6.

Input & Output

Example 1 — Small Number
$ Input: n = 13
Output: 6
💡 Note: Numbers 0-13: digit 1 appears in 1(×1), 10(×1), 11(×2), 12(×1), 13(×1) = total 6 times
Example 2 — Single Digit
$ Input: n = 9
Output: 1
💡 Note: Numbers 0-9: digit 1 appears only in number 1, so total is 1
Example 3 — Larger Number
$ Input: n = 99
Output: 20
💡 Note: Units place: 1,11,21,31,41,51,61,71,81,91 (10 ones). Tens place: 10-19 (10 ones). Total: 20

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Number of Digit One - Optimal Solution INPUT n = 13 Count 1s in: 0 to 13 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Contains digit 1 1s found: 1(1), 10(1), 11(2) 12(1), 13(1) Total: 1+1+2+1+1 = 6 ALGORITHM STEPS 1 Analyze by position Process each digit place 2 For each position i Calculate higher, curr, lower 3 Apply formula Count 1s at position 4 Sum all positions Return total count Position Analysis (n=13) Pos High Curr Low 1s 1s 1 3 0 2 10s 0 1 3 4 Total = 2 + 4 = 6 FINAL RESULT Output: 6 Total digit 1 occurrences in range [0, 13] Verification: 1 --> 1 one 10 --> 1 one 11 --> 2 ones 12,13 --> 2 ones Sum: 1+1+2+1+1 = 6 OK Complexity: Time: O(log n) Space: O(1) Key Insight: Instead of iterating through all numbers, analyze each digit position independently. For position i: count = higher * factor + adjustment based on current digit. If curr=0: count = higher * factor | If curr=1: count = higher * factor + lower + 1 | If curr>1: count = (higher+1) * factor TutorialsPoint - Number of Digit One | Optimal Solution (Mathematical Approach)
Asked in
Google 15 Microsoft 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen