-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Digits.cpp
80 lines (76 loc) · 1.76 KB
/
Count Digits.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
class Solution {
public:
/*
* param k : As description.
* param n : As description.
* return: How many k's between 0 and n.
*/
int count(int k, int n, char d, int pos, int len) {
int num = d - '0';
long base = pow(10, pos);
long base10 = base * 10;
int down = (n / base10) * base;
int up = down + base;
int right = n % base;
//cout << num << " " << down << " " << up << " " << right << endl;
//cout << base << " " << base10 << endl;
if(num < k) {
return down;
}
else if(num == k) {
return down + right + 1;
}
return up;
}
int digitCounts(int k, int n) {
// write your code here
if(n < 0) return -1;
if(k == 0 && n == 0) return 1;
vector<char> v;
int tmp = n;
while(tmp) {
v.push_back(char('0' + tmp % 10));
tmp /= 10;
}
int res= 0;
int len = v.size();
for(int i = 0; i < len; i++) {
res += count(k, n, v[i], i, len);
}
//cout << res << endl;
if(k == 0) {
for(int i = 1; i < len; i++) {
res -= pow(10, i);
}
}
return res;
}
int digitCounts1(int k, int n) {
int count = 0;
char ck = (char)(k + '0');
vector<char> v;
for(int i = k; i <= n; i++) {
v.clear();
int tmp = i;
while(tmp) {
v.push_back(char('0' + tmp % 10));
tmp /= 10;
}
for(int j = 0; j < v.size(); j++) {
if(v[j] == ck) count++;
}
}
return count;
}
};
int main() {
int k = 0;
int n = 9;
Solution s;
cout << s.digitCounts(k, n) << endl;
return 0;
}