forked from yunshouhu/InterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
面试题12之打印1到最大的n位数_Print1ToMaxOfNDigits.cpp
143 lines (116 loc) · 2.76 KB
/
面试题12之打印1到最大的n位数_Print1ToMaxOfNDigits.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Print1ToMaxOfNDigits.cpp : Defines the entry point for the console application.
//
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛
#include "stdafx.h"
#include <memory>
void PrintNumber(char* number);
bool Increment(char* number);
void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index);
// ====================方法一====================
void Print1ToMaxOfNDigits_1(int n)
{
if(n <= 0)
return;
char *number = new char[n + 1];
memset(number, '0', n);
number[n] = '\0';
while(!Increment(number))
{
PrintNumber(number);
}
delete []number;
}
// 字符串number表示一个数字,在 number上增加1
// 如果做加法溢出,则返回true;否则为false
bool Increment(char* number)
{
bool isOverflow = false;
int nTakeOver = 0;
int nLength = strlen(number);
for(int i = nLength - 1; i >= 0; i --)
{
int nSum = number[i] - '0' + nTakeOver;
if(i == nLength - 1)
nSum ++;
if(nSum >= 10)
{
if(i == 0)
isOverflow = true;
else
{
nSum -= 10;
nTakeOver = 1;
number[i] = '0' + nSum;
}
}
else
{
number[i] = '0' + nSum;
break;
}
}
return isOverflow;
}
// ====================方法二====================
void Print1ToMaxOfNDigits_2(int n)
{
if(n <= 0)
return;
char* number = new char[n + 1];
number[n] = '\0';
for(int i = 0; i < 10; ++i)
{
number[0] = i + '0';
Print1ToMaxOfNDigitsRecursively(number, n, 0);
}
delete[] number;
}
void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index)
{
if(index == length - 1)
{
PrintNumber(number);
return;
}
for(int i = 0; i < 10; ++i)
{
number[index + 1] = i + '0';
Print1ToMaxOfNDigitsRecursively(number, length, index + 1);
}
}
// ====================公共函数====================
// 字符串number表示一个数字,数字有若干个0开头
// 打印出这个数字,并忽略开头的0
void PrintNumber(char* number)
{
bool isBeginning0 = true;
int nLength = strlen(number);
for(int i = 0; i < nLength; ++ i)
{
if(isBeginning0 && number[i] != '0')
isBeginning0 = false;
if(!isBeginning0)
{
printf("%c", number[i]);
}
}
printf("\t");
}
// ====================测试代码====================
void Test(int n)
{
printf("Test for %d begins:\n", n);
Print1ToMaxOfNDigits_1(n);
Print1ToMaxOfNDigits_2(n);
printf("Test for %d ends.\n", n);
}
int _tmain(int argc, _TCHAR* argv[])
{
Test(1);
Test(2);
Test(3);
Test(0);
Test(-1);
return 0;
}