大整數相加
阿新 • • 發佈:2022-03-20
之前用過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; }