此题目中n是用整型数字表示的结果的最大位数,n最大为2147483647,而即使是long long 形式的数字,他也只能最大表示9.2*10^18,也就是最大表示19位数字,利用系统内置的数据类型完全不能满足要求,需要用字符串来表示大数。
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
#include<string>
using namespace std;
void PrintNum(string str)
{
bool dis = false; //控制前面的0不显示
for (int i = 0; i < str.size(); i++)
{
if (str[i] != '0'||dis==true)
{
cout << str[i];
dis = true;
}
}
cout << endl;
}
int main()
{
int n = 3;
//创建和n长度一致的字符串,并初始化为0
string result(n, '0');
int carry = 0; //进位
int len = result.size();
while (carry==0)
{
for (int i = result.size() - 1; i >= 0; i--)
{
int add = result[i] - '0'+1+carry;
if (i != result.size() - 1) //非最低位不需要加1
add--;
if (add >= 10)
{
carry = 1;
result[i] = add - 10 + '0';
}
else
{
carry = 0;
result[i] = add + '0';
break;
}
}
//显示结果
PrintNum(result);
}
system("pause");
return 0;
}