Formatted question description: https://leetcode.ca/all/1067.html
1067. Digit Count in Range
Level
Hard
Description
Given an integer d
between 0
and 9
, and two positive integers low
and high
as lower and upper bounds, respectively. Return the number of times that d
occurs as a digit in all integers between low
and high
, including the bounds low
and high
.
Example 1:
Input: d = 1, low = 1, high = 13
Output: 6
Explanation:
The digit d=1 occurs 6 times in 1,10,11,12,13. Note that the digit d=1 occurs twice in the number 11.
Example 2:
Input: d = 3, low = 100, high = 250
Output: 35
Explanation:
The digit d=3 occurs 35 times in 103,113,123,130,131,…,238,239,243.
Note:
0 <= d <= 9
1 <= low <= high <= 2×10^8
Solution
Calculate the number of times that d
occurs as a digit in all integers between 1 and high
, and calculate the number of times that d
occurs as a digit in all integers between 1 and low - 1
. Then calculate the difference between the two numbers of times to obtain the result.
If d
is not 0, the number of times is calculated as follows.
- Loop over
i
from 1 ton
. Each time seti *= 10
. - The value
n / (i * 10) * i
represents the number of digitd
at digiti * 10
. - The value
Math.min(Math.max(n % (i * 10) - d * i + 1, 0), i)
represents the extra number of digitd
at digiti * 10
. - Calculate the number of times of
d
by calculating the sum of the values in the previous two steps.
If d
is 0, the number of times is calculated as follows.
- Loop over
i
from 1 ton / 10
. Each time seti *= 10
. - The value
(n / (i * 10) - 1) * i
represents the number of digitd
at digiti * 10
. - The value
Math.min(Math.max(n % (i * 10) - d * i + 1, 0), i)
represents the extra number of digitd
at digiti * 10
. - Calculate the number of times of
d
by calculating the sum of the values in the previous two steps.
The difference exists because digit 0 cannot appear at the highest digit, except the number 0. However, in this problem, both low
and high
are positive integers, so 0 is never in the range.
class Solution {
public int digitsCount(int d, int low, int high) {
long highCount = countDigits(high, d);
long lowCount = countDigits(low - 1, d);
int count = (int) (highCount - lowCount);
return count;
}
public long countDigits(int n, int digit) {
if (n <= 0)
return 0;
long count = 0;
if (digit == 0) {
for (long i = 1; i <= n / 10; i *= 10) {
long unit = i * 10;
count += (n / unit - 1) * i + Math.min(i, Math.max(0, n % unit - digit * i + 1));
}
} else {
for (long i = 1; i <= n; i *= 10) {
long unit = i * 10;
count += n / unit * i + Math.min(i, Math.max(0, n % unit - digit * i + 1));
}
}
return count;
}
}