-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq17.6.cpp
42 lines (31 loc) · 904 Bytes
/
q17.6.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
#include <iostream>
using namespace std;
void print_number_twos(int n) {
int current_multiple = 10, totalCount = 0;
int q, rem;
while (current_multiple < n * 10) {
q = n / current_multiple;
rem = n % current_multiple;
totalCount += q * (current_multiple / 10);
if (rem >= 3 * (current_multiple / 10))
totalCount += (current_multiple / 10);
else if ((2 * current_multiple / 10) <= rem)
totalCount += (rem - (2 * current_multiple / 10) + 1);
current_multiple *= 10;
}
cout << "total number of 2's in numbers from 0 to " << n << " : "
<< totalCount << endl;
return;
}
int main(void) {
int n;
while (true) {
cout << "enter value of n to count number of 2's from 0 to n or enter 0 to "
"exit: ";
cin >> n;
if (n == 0)
break;
print_number_twos(n);
}
return 0;
}