-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNumber-Of-Digit-One.cpp
54 lines (54 loc) · 1016 Bytes
/
Number-Of-Digit-One.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
// Solution1:
class Solution {
public:
int countDigitOne(int n) {
int res =0;
if (n<1)
return res;
for (int i=1;i<=n;i++)
{
res+=NumberOf1(i);
}
return res;
}
int NumberOf1(int n)
{
int num =0;
while(n)
{
if (n%10==1)
{
num++;
}
n /= 10;
}
return num;
}
};
// Solution 2:
class Solution {
public:
int countDigitOne(int n) {
long int res = 0;
for (long int i=1;i<=n;i*=10)
{
long int a = n/i;
long int b = n%i;
res += (a+8)/10*i + (a%10==1)*(b+1);
}
return res;
}
};
// Solution 3:
class Solution {
public:
int countDigitOne(int n)
{
int res = 0;
for (int i = 1; i <= n; i++) {
string str = to_string(i);
res += count(str.begin(), str.end(), '1');
}
return res;
}
};