Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Input: n = 13
Output: 6
Input: n = 0
Output: 0
0 <= n <= 109This basic solution involves iterating through each number from 1 to n and counting the number of times the digit 1 appears. Though simple, this approach lacks efficiency.
For each number, convert it to a string and count the occurrences of '1'. Sum the counts across all numbers.
While the brute-force solution checks each number individually, an optimal approach models a mathematical pattern based on the position of each digit.
Consider how many 1s appear at each digit through the entire sequence from 0 to n. By calculating the contribution of 1s for units, tens, hundreds places independently, a more efficient solution is derived.
For each digit in the number, split the number into three parts: higher, current, and lower part. Compute possible occurrences of 1 considering each position as the current digit.
n.