1. 问题描述
输入数字n,按顺序打印出从1到最大的n位十进制数。
比如输入3,则打印出1,2,3,... ,一直到最大的3位数即 999.
注意的问题:考虑大数的情形导致的溢出。
2. 算法1
使用字符串数组表示大数,在字符数组上模拟整数的加法(加 1 );
字符串数组中每个元素都是 ‘0’ 到 ‘9’ 之间的某一个字符。初始化时将每一个字符都设置为 ‘0’, 相当于整数 0 .
#include <iostream>
#include <string>
using namespace std;
// print the integers characters array.
// if current interger is 123, the integer characters array looks like as below
// a[0], a[1], a[2], a[3]
// '3' '2' '1' '0'
// the order is opposite to real interger order, so we need to print the characters array form the first non '0' element with reversed order.
void printInteger(char* pStrIntegers, int size)
{
if (pStrIntegers == NULL || size <= 0)
{
return;
}
bool isPrint = false;
for (int i = size - 1; i >= 0; i--)
{
if (!isPrint)
{
if(pStrIntegers[i] != '0')
{
isPrint = true;
cout<<pStrIntegers[i];
}
}else
{
cout<<pStrIntegers[i];
}
}
cout<<endl;
}
// add 1 to current integer, mock addition operation on the charaters array.
bool incrementone(char* pStrIntegers, int size)
{
if (pStrIntegers == NULL || size <= 0)
{
return false;
}
bool isValid = true;
// for 0 ~ size-1 th elements
// try to add 1 from the first character: pStrIntegers[0]
// from 1th element to nth elements
for (int i = 0; i < (size - 1); i++)
{
if (pStrIntegers[i] != '9')
{
pStrIntegers[i] = pStrIntegers[i] + 1; // if current character is not '9', then just add 1 on current characte.
break; // end this increment, add 1 successfully.
}else
{
// current character is '9', adding 1 should carry.
// go to next character element, meanwhile set current character to '0'.carry
pStrIntegers[i] = '0';
// if current character is in the last valid index, this increment is invalid, as current character should be like "999..999".
if (i == (size - 2))
{
isValid = false;
}
}
}
return isValid;
}
void printToMaxOfInteger(int n)
{
if (n <= 0)
{
cout<<"Invalid n = "<<n<<endl;
return;
}
cout<<"Start to print n = "<<n<<endl;
// declare a character array with capacity n + 1
char strIntegers[n + 1];
// initialize all the characters as '0'.
for (int i = 0; i <= n; i++)
{
strIntegers[i] = '0';
}
// start to increment by 1.
while (incrementone(strIntegers, n + 1))
{
printInteger(strIntegers, n + 1);
}
}
int main(int argc, const char * argv[])
{
printToMaxOfInteger(3);
printToMaxOfInteger(-1);
printToMaxOfInteger(0);
return 0;
}
2. 算法2
使用全排列。
参考:剑指offer 名企面试官精讲典型编程题》 - 面试题12:打印1到最大的n位数