题解 | #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")

全部评论

相关推荐

06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
喜欢飞来飞去的雪碧在...:可以试一试字节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务