-
Notifications
You must be signed in to change notification settings - Fork 257
/
digit-counts.cpp
62 lines (54 loc) · 1.45 KB
/
digit-counts.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Time: O(logn) = O(1)
// Space: O(1)
class Solution {
public:
/*
* param k : As description.
* param n : As description.
* return: How many k's between 0 and n.
*/
int digitCounts(int k, int n) {
int cnt = 0, multiplier = 1, left_part = n;
while (left_part > 0) {
// split number into: left_part, curr, right_part
int curr = left_part % 10;
int right_part = n % multiplier;
// count of (c000 ~ oooc000) = (ooo + (k < curr)? 1 : 0) * 1000
cnt += (left_part / 10 + (k < curr)) * multiplier;
// if k == 0, oooc000 = (ooo - 1) * 1000
if (k == 0 && multiplier > 1) {
cnt -= multiplier;
}
// count of (oook000 ~ oookxxx): count += xxx + 1
if (curr == k) {
cnt += right_part + 1;
}
left_part /= 10;
multiplier *= 10;
}
return cnt;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
/*
* param k : As description.
* param n : As description.
* return: How many k's between 0 and n.
*/
int digitCounts(int k, int n) {
int cnt = 0;
for (int i = 0; i <= n; ++i) {
int num = i;
while (num > 0) {
if (num % 10 == k) {
++cnt;
}
num /= 10;
}
}
return cnt;
}
};