文章

9

粉丝

1

获赞

124

访问

2.3k

头像
大整数加法 题解: C++ string 存储,按位加,逆序输出
P1474 武汉大学机试题
发布于2026年2月10日 11:08
阅读数 118

  1. 思路:字符串存储 a ,b ,输出字符串 result ,对 a b 从各自的最后一位进行加,得到的结果 temp = anum + bnum + carry; 将其余数加入到 result 中, carry = temp / 10;

  2. 注意点:判断条件是 a b 或者 carry 都不为零。

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

string addStr(string a, string b){
    string result;
    int i = a.size() - 1;
    int j = b.size() - 1;
    int carry = 0;
    // 前两个条件用于不等长的 a b, carry > 0 用于 9 + 1 = 10 的情况
    while(i >= 0 || j >= 0 || carry > 0){
        int anum = i >= 0 ? a[i] - '0' : 0;
        int bnum = j >= 0 ? b[j] - '0' : 0;

        int temp = anum + bnum + carry;
        result.push_back('0' + (temp % 10));
        carry = temp / 10; // 只会有 0 或者 1

        i--;
        j--;
    }
    reverse(result.begin(), result.end());
    return result;
}

int main(){
    string a,b;
    while(cin >> a >> b){
        string result = addStr(a,b);
        cout << result << endl;
...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发