NOTE
Number of Digit 1 Occurrences
Given an integer n, count how many times the digit 1 appears in all integers from 1 through n.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Find how many times digit 1 appears among the integers from 1 to 13, and then calculate how many times it appears from 100 to 1300. ACMer counted manually: the numbers containing 1 from 1 to 13 are 1, 10, 11, 12, and 13, for a total of 6 occurrences. But the second question leaves him stuck. He hopes you can help and generalize the problem so that the number of 1s appearing in any non-negative integer range can be calculated quickly (the number of 1s from 1 to n).
2. Approach
- Modulo
3. Implementation
func NumberOf1Between1AndN_Solution(n int) int {
count := 0
for i := 1; i <= n; i++ {
j := i
for j != 0 {
if j%10 == 1 {
count++
}
j /= 10
}
}
return count
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub