题解 | #a+b#
a+b
https://www.nowcoder.com/practice/4c39c984ea3848b48e111b8e71ec1dd4
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
//这种大精度 处理起来就是当字符串看 去处理
struct bign{
int digits[1001]; //自己写了一遍 才知道这里用静态存储后面会遍历点 这里采用十进制低位存低位 高位存高位
int lens; //数组长度
bign(){ //初始化
memset(digits,0, sizeof(digits));
lens = 0;
}
};
bign add(bign a, bign b){ //加法操作
bign answer;
int carry = 0;
int len = max(a.lens,b.lens);
for(int i = 0, j = 0; i < a.lens || j < b.lens; i++,j++){
int current = a.digits[i] + b.digits[j] + carry; //本位加进位
answer.digits[answer.lens++] = current % 10;
carry = current / 10;
}
if(carry == 1) {
answer.digits[answer.lens++] = 1;
}
return answer;
}
int main() {
string a, b;
while (cin >> a >> b) { // 注意 while 处理多个 case
bign an,bn;
an.lens = a.size();
bn.lens = b.size();
for(int i = 0; i < a.size(); i++){
an.digits[an.lens - i - 1] = a[i] - '0';
}
for(int i = 0; i < b.size(); i++){
bn.digits[bn.lens - i - 1] = b[i] - '0';
}
bign res = add(an,bn);
for(int i = res.lens - 1; i >= 0; i--){
cout << res.digits[i];
}
cout << endl;
}
}
// 64 位输出请用 printf("%lld")
查看16道真题和解析