forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1067.Digit-Count-in-Range.cpp
45 lines (40 loc) · 1.17 KB
/
1067.Digit-Count-in-Range.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
int digitsCount(int d, int low, int high)
{
return helper(d, high)-helper(d,low-1);
}
int helper(int d, int n)
{
string s = to_string(n);
int len = s.size();
int count = 0;
if (d!=0)
{
for (int i=1; i<=len; i++)
{
int divisor = pow(10,i);
count += n/divisor * pow(10,i-1);
int y = s[len-i]-'0';
if (y > d)
count += pow(10,i-1);
else if (y==d)
count += n%(int)(pow(10,i-1)) + 1;
}
}
else
{
for (int i=1; i<len; i++)
{
int divisor = pow(10,i);
count += (n/divisor-1) * pow(10,i-1);
int y = s[len-i]-'0';
if (y > d)
count += pow(10,i-1);
else if (y==d)
count += n%(int)(pow(10,i-1)) + 1;
}
}
return count;
}
};