[LeetCode] Digit Count in Range

1067. Digit Count in Range

Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, right].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
long helper(int num, int d) {
long right = num, left = 0;
long sum = 0, p = 1;
while(right) {
int n = right % 10;
right /= 10;

sum += right * p;
if(d) {
if(n == d) sum += left + 1;
else if(n > d) sum += p;
left = left + p * n;
} else {
left = left + p * n;
if(right and p > 1) {
sum -= p;
sum += min(left + 1, p);
}
}
p *= 10;
}
return sum;
}
public:
int digitsCount(int d, int low, int high) {
return helper(high, d) - helper(low - 1, d);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/12/PS/LeetCode/digit-count-in-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.