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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code