题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include <iostream> #include <algorithm> #include <string> using namespace std; string sumString(string& num1,string &num2) { string smaller = num1.size()>num2.size()? num2:num1; string bigger = num1.size()>num2.size()? num1:num2; int last = 0; reverse(smaller.begin(),smaller.end()); reverse(bigger.begin(),bigger.end()); //从最低位置进行增加 string result; for(int i = 0;i!=smaller.size();++i) { int n1 = static_cast<int>(smaller[i]-'0'); int n2 = static_cast<int>(bigger[i]-'0'); n2 += (n1+last); if(n2>9) { result.push_back(static_cast<char>(n2-10+'0')); last = 1; } else { result.push_back(static_cast<char>(n2+'0')); last = 0; } } for(int i = smaller.size();i!=bigger.size();++i) { int n1 = static_cast<int>(bigger[i]-'0'); n1+=last; if(n1>9) { result.push_back(static_cast<char>(n1+'0'-10)); last = 1; } else { result.push_back(static_cast<char>(n1+'0')); last = 0; } } if(last!=0) result.push_back(static_cast<char>(1+'0')); reverse(result.begin(), result.end()); return result; } int main() { string num1; string num2; getline(cin, num1); getline(cin,num2); cout<<sumString(num1, num2); } // 64 位输出请用 printf("%lld")
反向处理,然后从后到前