Problem Description
Count the total number of digit 1 appearing in all non-negative integers less than or equal to a given integer n.
Key Insights
- Analyze each digit position in n (ones, tens, hundreds, etc.) independently.
- For each digit position, decompose n into three parts: high (digits left of the current position), current (the digit at the current position), and low (digits right of the current position).
- Depending on the value of the current digit:
- If it is 0, its contribution is solely defined by the higher digits.
- If it is 1, count both the higher digits and the remainder (low) plus one.
- If it is greater than 1, the contribution is fully determined by the higher digits incremented by one.
- This mathematical method avoids inefficient iterations and leverages place value analysis.
Space and Time Complexity
Time Complexity: O(log n) because the number of digits in n determines the loop iterations. Space Complexity: O(1) as only a few integer variables are used.
Solution
We use a mathematical approach by iterating over each digit position. At each position, calculate:
- high: n divided by the current digit place multiplied by 10.
- current: the digit at the current position from n.
- low: the remainder when n is divided by the current digit place. Based on the value of the current digit, determine its contribution to the total count of 1's using specific formulae:
- If current == 0: add high * i.
- If current == 1: add high * i + (low + 1).
- Else: add (high + 1) * i. This algorithm efficiently counts the digit 1 occurrences without iterating through every number from 0 to n.