基于C++的string方法来解决大数相加问题

本文介绍了一种解决大数相加问题的算法,通过使用字符串存储超长数字,并逐位进行加法运算,有效处理了无法用常规整型变量表示的大数加法。文章详细展示了算法的实现过程,包括进位处理和最终结果的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大数相加问题一直是一个很经典的算法问题。给定两个非常非常大,大到超越了不可能用int,long long int等类型表示的数字,所以就要用其他的方法。
我的解决方案是使用两个string来保存数字,然后再模拟两个数字相加的情况。最后再输出。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    string a,b,c="";
    cin >> a >> b;
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    int i = 0,carry = 0,num1,num2,adds;
    while(i < a.size() && i < b.size()){
        num1 = (a[i] - '0');
        num2 = (b[i++] - '0');
        c.push_back('0' + (num1 + num2 + carry)%10);
        carry = (num1 + num2 + carry)/10;
    }
    while(i < a.size()){
        num1 = (a[i++] - '0');
        c.push_back('0' + (num1 + carry)%10);
        carry = (carry + num1)/10;
    }
    while(i < b.size()){
        num2 = (b[i++] - '0');
        c.push_back('0' + (num2 + carry)%10);
        carry = (carry + num2)/10;
    }
    while(carry){
        c.push_back('0' + (carry)%10);
        carry /= 10;
    }
    reverse(c.begin(),c.end());
    cout << c;
    return 0;
}
sample input:
99999 1
sample output:
100000
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值