HJ57 High precision integer addition ●●
describe
Enter two integers represented by the string str, and find the sum of the numbers represented by them.
Data range: 1 ≤ len ( str ) ≤ 10000 1 \le len(str) \le 100001≤l e n ( s t r )≤10000
Enter a description:
Enter two strings. Ensure that the string contains only '0'~'9' characters
Output description:
Output the summed result
example
Input:
9876543210
1234567890
Output:
11111111100
answer
1. Simulation
Process the two long strings
from end to end, add them bit by bit, push the single digit result into the stack , and record the value of extra_add, add bit by bit again in the next cycle, and finally
pop the stack one by one.
Time complexity, space complexity: O ( n ) O(n)O ( n )
#include <iostream>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
string s1, s2;
while(cin >> s1 >> s2){
int len1 = s1.length(), len2 = s2.length(); // 字符串长度
int idx1 = len1-1, idx2 = len2-1; // 指针下标
int extra_add = 0, temp = 0;
stack<char> st;
while(idx1 >= 0 || idx2 >= 0){
int num1 = 0, num2 = 0;
if(idx1 >= 0) num1 = s1[idx1--] - '0'; // 加数
if(idx2 >= 0) num2 = s2[idx2--] - '0'; // 加数
temp = extra_add + num1 + num2; // 和 0~18
if(temp >= 10){
extra_add = 1; // 进位
}else{
extra_add = 0;
}
st.push(temp%10 + '0'); // 个位数入栈
}
if(extra_add == 1) cout << '1'; // 可能的进位
while(!st.empty()){
// 出栈输出
cout << st.top();
st.pop();
}
}
return 0;
}