大整数相加
之前用过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; }

浙公网安备 33010602011771号