题解 | #高精度整数加法#

高精度整数加法

https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1, str2;
    cin >> str1 >> str2;
    int idx1 = str1.size() - 1, idx2 = str2.size() - 1;
    int carry = 0;
    string res;
    // 倒序遍历,逐个相加,并转成字符串处理
    while (idx1 >= 0 || idx2 >= 0) {
      int num1 = 0;
      int num2 = 0;
      // 两个字符串都有效
      if (idx1 >= 0 && idx2 >= 0) {
        num1 = stoi(str1.substr(idx1, 1));
        num2 = stoi(str2.substr(idx2, 1));
      }
      // 只有str2有效
      if (idx1 < 0) {
        num2 = stoi(str2.substr(idx2, 1));
      }
      // 只有str1有效
      if (idx2 < 0) {
        num1 = stoi(str1.substr(idx1, 1));
      }
      // 累加
      int sum = num1 + num2 + carry;
      // 保存进位
      carry = sum / 10;
      sum %= 10;
      // 保存当前位置结果
      res = std::to_string(sum) + res;
      idx1--;
      idx2--;
    }
    // 增加最后的进位
    if (carry) {
      res = std::to_string(carry) + res;
    }
    cout << res << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不愿透露姓名的神秘牛友
01-08 16:50
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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