大数相加
作者:
Emma
,
2019-07-05 14:40:29
,
所有人可见
,
阅读 928
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string str1 , str2;
getline(cin , str1);
getline(cin , str2);
if(str1.length() < str2.length())
swap(str1 , str2);
int m=str1.length() , n=str2.length();
reverse(str1.begin() , str1.end());
reverse(str2.begin() , str2.end());
int carry=0;
int currentNum;
int i;
for(i=0; i<n; i++){
currentNum = str1[i] -'0' + str2[i] -'0' + carry;
carry = currentNum / 10;
currentNum %= 10;
str1[i] = currentNum + '0';
}
if(n < m){
for(i=n; i<m; i++){
currentNum = str1[i] -'0' + carry;
carry = currentNum / 10;
currentNum %= 10;
str1[i] = currentNum + '0';
}
}
if(carry > 0){
str1 = str1 + '1';
}
reverse(str1.begin() , str1.end());
cout<<str1;
}