题目:传送门
解答:大数(范围超过可表示精度)加法,C++没有java的相应的大数类,直接用字符串模拟。几个小trick:
- 考虑两个数的长度,可以刚刚开始就将两者顺序调换(加法交换律),使得第一个为更长的数;
- 字符转换成数字:number = s - '0';
- 数字转换成字符:s = (char)(number + '0');
- 一开始不清楚结果是几位数,可以先倒序模拟,最后再倒序还原。
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
int t;
cin>>t;
string pa, pb, a, b, c, tmp;
vector<char> save;
int jinwei, sum;
for (int k = 0; k < t; k++)
{
cin>>pa>>pb;
save.clear();
c.clear();
// 重置顺序!但是保留原先的数值
if(pa.size() < pb.size())
{
a = pb;
b = pa;
}
else
{
a = pa;
b = pb;
}
int maxlen = a.size();
int minlen = b.size();
sum = 0;
jinwei = 0;
int i = maxlen;
int j = minlen;
while((i--) && (j--))
{
sum = a[i] - '0' + b[j] - '0';
if(jinwei) sum++;
if(sum > 9)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
save.push_back((char)(sum % 10 + '0'));
}
/*if ((maxlen - minlen) != 0)
{*/
for (i = (maxlen - minlen - 1); i >= 0 ; i--)
{
sum = a[i] - '0';
if(jinwei) sum++;
if(sum > 9)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
save.push_back((char)(sum % 10 + '0'));
}
//}
if(jinwei)
{
save.push_back('1');
}
for (int i = save.size() - 1; i>=0 ; i--)
{
c = c + save[i];
}
printf("Case %d:\n", k+1);
cout<<pa<<" + "<<pb<<" = "<<c<<endl;
if (k != t - 1)
{
cout<<endl;
}
}
return 0;
}