题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
从最后一位开始正常的累加,当前位为sum / 10,进位为sum % 10,每一位存的结果存在stack中,最后输出stack即可
#include <iostream>
#include <stack>
using namespace std;
int main() {
string num1, num2;
while (cin >> num1 >> num2) {
int i = num1.length() - 1, j = num2.length() - 1, n1, n2, carry = 0;
stack<int> st;
while (i >= 0 || j >= 0 || carry > 0) {
n1 = i >= 0 ? num1[i] - '0' : 0;
n2 = j >= 0 ? num2[j] - '0' : 0;
st.push((n1 + n2 + carry) % 10);
carry = (n1 + n2 + carry) / 10;
i--;
j--;
}
while (st.size()) {
cout << st.top();
st.pop();
}
cout << endl;
}
}
查看2道真题和解析
拼多多集团-PDD公司福利 817人发布