For every integer x from 1 to n, we write down the integer obtained by removing all zeros from the decimal representation of x.
Return an integer denoting the number of distinct integers written down.
Example 1:
Input:n = 10
Output:9
Explanation:
The integers we wrote down are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1. There are 9 distinct integers (1, 2, 3, 4, 5, 6, 7, 8, 9).
Example 2:
Input:n = 3
Output:3
Explanation:
The integers we wrote down are 1, 2, 3. There are 3 distinct integers (1, 2, 3).
Constraints:
1 <= n <= 1015
Solutions
Solution 1: Digit DP
The problem essentially asks us to count the number of integers in the range \([1, n]\) that do not contain the digit 0. We can solve this problem using digit DP.
We design a function \(\text{dfs}(i, \text{zero}, \text{lead}, \text{limit})\), which represents the number of valid solutions when we are currently processing the \(i\)-th digit of the number. We use \(\text{zero}\) to indicate whether a non-zero digit has appeared in the current number, \(\text{lead}\) to indicate whether we are still processing leading zeros, and \(\text{limit}\) to indicate whether the current number is constrained by the upper bound. The answer is \(\text{dfs}(0, 0, 1, 1)\).
In the function \(\text{dfs}(i, \text{zero}, \text{lead}, \text{limit})\), if \(i\) is greater than or equal to the length of the number, we can check \(\text{zero}\) and \(\text{lead}\). If \(\text{zero}\) is false and \(\text{lead}\) is false, it means the current number does not contain 0, so we return \(1\); otherwise, we return \(0\).
For \(\text{dfs}(i, \text{zero}, \text{lead}, \text{limit})\), we can enumerate the value of the current digit \(d\), then recursively calculate \(\text{dfs}(i+1, \text{nxt\_zero}, \text{nxt\_lead}, \text{nxt\_limit})\), where \(\text{nxt\_zero}\) indicates whether a non-zero digit has appeared in the current number, \(\text{nxt\_lead}\) indicates whether we are still processing leading zeros, and \(\text{nxt\_limit}\) indicates whether the current number is constrained by the upper bound. If \(\text{limit}\) is true, then \(up\) is the upper bound of the current digit; otherwise, \(up\) is \(9\).
The time complexity is \(O(\log_{10} n \times D)\) and the space complexity is \(O(\log_{10} n)\), where \(D\) represents the count of digits from 0 to 9.