forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.4.cpp
82 lines (68 loc) · 1.64 KB
/
20.4.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
81
82
#include <iostream>
using namespace std;
int Count2(int n){
int count = 0;
while(n > 0){
if(n%10 == 2)
++count;
n /= 10;
}
return count;
}
int Count2s1(int n){
int count = 0;
for(int i=0; i<=n; ++i)
count += Count2(i);
return count;
}
int Count2s(int n){
int count = 0;
int factor = 1;
int low = 0, cur = 0, high = 0;
while(n/factor != 0){
low = n - (n/factor) * factor;//低位数字
cur = (n/factor) % 10;//当前位数字
high = n / (factor*10);//高位数字
switch(cur){
case 0:
case 1:
count += high * factor;
break;
case 2:
count += high * factor + low + 1;
break;
default:
count += (high + 1) * factor;
break;
}
factor *= 10;
}
return count;
}
int Countis(int n, int i){
if(i<1 || i>9) return -1;//i只能是1到9
int count = 0;
int factor = 1;
int low = 0, cur = 0, high = 0;
while(n/factor != 0){
low = n - (n/factor) * factor;//低位数字
cur = (n/factor) % 10;//当前位数字
high = n / (factor*10);//高位数字
if(cur < i)
count += high * factor;
else if(cur == i)
count += high * factor + low + 1;
else
count += (high + 1) * factor;
factor *= 10;
}
return count;
}
int main(){
for(int i=1; i<1000; ++i)
cout<<Count2s1(i)<<" "<<Count2s(i)<<" "<<Countis(i, 2)<<endl;
// int n = 999;
// for(int i=1; i<10; ++i)
// cout<<Countis(n, i)<<endl;
return 0;
}