题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include <algorithm> #include <iostream> #include <string> using namespace std; int main() { string str1,str2; cin>>str1>>str2; int m=str1.size(),n=str2.size(); int sum=0; int carry=0;//进位 string ans=""; int i=m-1,j=n-1; while(i>=0 || j>=0) { int num1,num2; //判断字符串是否还有字符 num1 = (i>=0) ? (str1[i]-'0') : 0; num2 = (j>=0) ? (str2[j]-'0') : 0; sum = num1 + num2+carry; carry =sum /10;//进位 ans+=(sum % 10)+'0'; i--; j--; } if(carry != 0) ans+= to_string(carry); reverse(ans.begin(), ans.end()); cout<<ans<<endl; return 0; }