大整数相加

之前用过char*,int。见字符串处理 - 完全感覚Dreamer - 博客园 (cnblogs.com)

这次用string,里面用到了reverse函数比较方便。

复制代码
#include <bits/stdc++.h>
using namespace std;

void add(string a,string b){
    string res;
    int carry=0,temp=0,i;
    for(i=0;i<a.size()&&i<b.size();i++){
        temp=a[i]+b[i]-'0'-'0'+carry;
        res+=(temp%10+'0');
        carry=temp/10;
    }
    while(i<a.size()){
        temp=a[i]-'0'+carry;
        res+=(temp%10+'0');
        carry=temp/10;
        i++;
    }
    while(i<b.size()){
        temp=b[i]-'0'+carry;
        res+=(temp%10+'0');
        carry=temp/10;
        i++;
    }
    if(carry)
        res+='1';
    reverse(res.begin(),res.end());
    cout<<res<<endl;
}

int main(){
    string str1,str2;
    cin>>str1>>str2;
    reverse(str1.begin(),str1.end());
    reverse(str2.begin(),str2.end());
    add(str1,str2);
    //cout<<str1<<endl;
    //cout<<res<<endl;
    return 0;
}
复制代码

 

posted @   完全感覚Dreamer  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示