剑指offer用的是字符串,还要苦逼的字符串比较,看是否进位。
直接用整型数组来保存。
#include <iostream>
#include <iomanip>
using namespace std;
//一个int保存几位数
const int int_num = 2;
//每位数最大值,超过这个要进位(不包括最高位)
const int int_max = 99;
void func()
{
//n为要显示的最大位数,len为需要int数组的长度,这里简化了,直接给出来
int n = 5, len = 3;
//最高位最大为9
int high_int_max = 9;
int* a = new int[len];
int count=1;
int i, j, c;
while(1)
{
//最低位加一
i=0;
a[i]++;
//处理进位
if(a[i] == int_max+1)
{
a[i] = 0;
j=i+1;
c = 1;
//处理已使用的int元素
while(j<count)
{
a[j]++;
if(a[j] == int_max+1)
{
a[j] = 0;
j++;
c = 1;
}
else
{
c = 0;
break;
}
}
//增加一个int元素,作为新的最高位
if(c==1)
{
if(count<len)
{
count++;
a[count-1] = 1;
}
else
return ;
}
}
//结束条件
if(a[len-1] > high_int_max)
return ;
//输出最高位的int
cout<<a[count-1];
//其他位的int,注意宽度为全局变量int_num,不足的要补0
for(i=count-2; i>=0; i--)
cout<<setfill('0')<<setw(2)<<a[i];
cout<<endl;
}
}
int main()
{
func();
return 0;
}