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
Count Digit 1 in Numbers 0 to 13Numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1311 digit 1101 digit 1112 digit 1s121 digit 1131 digit 1Numbers with digit 1: 1, 10, 11, 12, 13Count of digit 1s: 1 + 1 + 2 + 1 + 1 = 6Output: 6Total occurrences
Understanding the Visualization
1
Input Range
Given n=13, check numbers 0,1,2,...,13
2
Count 1s
Find all occurrences of digit 1
3
Output Total
Return total count of 1s
Key Takeaway
🎯 Key Insight: Use mathematical patterns to count 1s by digit position instead of checking every number
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