大整数相加
之前用过char*,int。见
这次用string,里面用到了reverse函数比较方便。
#includeusing namespace std; void add(string a,string b){ string res; int carry=0,temp=0,i; for(i=0;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< endl; } int main(){ string str1,str2; cin>>str1>>str2; reverse(str1.begin(),str1.end()); reverse(str2.begin(),str2.end()); add(str1,str2); //cout< //cout< return 0; }