思路:因为a,b≤10 的五百次方数据远远大于long long型
所以我们应该使用数组或字符串模拟计算过程
以下使用字符串模拟
写代码时的注意点:
1.考虑数字长度不同和相同两种情况
2.考虑进位问题
3.考虑数字长度不同时,较长的字符串加上较短的字符串时连续进位。
(例99999+1和1+99999)
#include<bits/stdc++.h>
using namespace std;
#include<string>
#include<iostream>
int main()
{
string a;//整体思路,将字符串反转,单独计算每个字符,大于10,往后一位加1
string b;//长度相同时比较简单,长度不同时 需要多考虑第一个while循环后,连续进位,所以再使用一个while循环来进位
string c="";
string temp;//当a与b大小不同时,把较长的字符串付给temp字符串
cin>>a>>b;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());//反转数字用于从后往前计算
int count=0;int j=0;//j用来存储满10的进1的数,count用来一个个遍历前n个相同长度的数字
int length;
if(a.size()!=b.size()){
if(a.size()<b.size())//
{
length=a.size();//取最小长度
temp=b;//把较长的字符串付给temp字符串
}
else {
length=b.size();
temp=a;
}
while(length>count){//例:123456+12;计数前两个
c+=to_string((a[count]-'0'+b[count]-'0'+j)%10);//将两个字符转为数字计算再+j,然后再转为字符加到c字符串中
j=(a[count]-'0'+b[count]-'0'+j)/10;
count++;
}
if(j>=1)
{//例:9999999+1
while(j&&length<temp.size()){
c+=to_string((temp[length]-'0'+j)%10);//例:5+9取4
length++;
j=(temp[length]-'0'+j)/10;//例5+9取1
}
if(length==temp.size())//length==a.size()时说明两数相加大于输入的最长字符串了,所以在后加1
{
c+='1';
}
else
c+=temp.substr(length);//length!=a.size()时说明两数相加不于输入的最长字符串了,所以在后加a的剩余字符串即可
}
else
c+=temp.substr(length);
reverse(c.begin(),c.end());
cout<<c;
}
else
{ length=a.size();
while(length>count){
c+=to_string((a[count]-'0'+b[count]-'0'+j)%10);
j=(a[count]-'0'+b[count]-'0'+j)/10;
count++;
}
if(j>=1)
{
c+=to_string(j);
}
reverse(c.begin(),c.end());//反转c字符串,得到结果
cout<<c;
}
}