C/C++ 每日一题
超长正整数的相加,题目链接:https://www.nowcoder.com/practice/5821836e0ec140c1aa29510fd05f45fc?tpId
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;string AddLongInteger(string addend, string augend){
int i = 0,n=addend.size()>augend.size()?n=addend.size():n=augend.size(); //n为较长计算值的长度,用来循环计算时使用
string c; //计算结果保存的值
int temp, tep = 0; //进位值要记得初始化
reverse(addend.begin(), addend.end()); //这里将两个加数都翻转过来计算,主要是为了写入结果的时候可以直接使用‘+=’
reverse(augend.begin(), augend.end()); //当然也可以没有这一步,直接从后往前算
for (; i < n; i++){
int a = i<addend.size() ? addend[i] - '0' : 0; //若是一个加数已经全部计算完成,在接下来就用0代替来计算
int b = i<augend.size() ? augend[i] - '0' : 0;
temp = (a+b+tep)% 10; //计算结果值(要填入结果的值)
tep = (a + b + tep) / 10; //进位值
c += temp + 48; // 填入结果
}
if (tep>0){ //若是最后一位计算有进位值,则直接填入结果
c += tep+'0';
}
reverse(c.begin(), c.end()); //将计算结果反过来就是正确结果
return c;
}
int main(){
string a, b, c;
while (cin >> a >> b){
cout << AddLongInteger(a, b) << endl;
}
return 0;
}

浙公网安备 33010602011771号