-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path17_print_1_to_max_of_n_digits.cc
66 lines (55 loc) · 1.3 KB
/
17_print_1_to_max_of_n_digits.cc
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
#include <iostream>
#include <string.h>
using namespace std;
class Solution {
public:
void print_1_to_max_of_n_digits(int n) {
if (n <= 0) {
return;
}
char *str = new char[n+1];
memset(str, '0', n);
str[n] = '\0';
while (increment(str, n)) {
print(str);
}
delete [] str;
}
private:
static bool increment(char *str, const int n) {
int take = 0;
for (int i = n-1; i >= 0; i--) {
int num = str[i]-'0'+take;
if (i == n-1) {
++num;
}
if (num >= 10) {
if (i == 0) {
// Overflow.
return false;
}
int units = num-10;
take = 1;
str[i] = units+'0';
} else {
str[i] = num+'0';
break;
}
}
return true;
}
static void print(const char *str) {
const char *p = str;
while (*p == '0') {
p++;
}
cout << p << endl;
}
};
int main(int argc, char const *argv[])
{
Solution().print_1_to_max_of_n_digits(1);
Solution().print_1_to_max_of_n_digits(2);
Solution().print_1_to_max_of_n_digits(3);
return 0;
}