#include<stdio.h>
#include<stack>
#include<vector>
using namespace std;
stack<int> c,d;//stack for add large number
int main(){
char a[100]={'0',};
char b[100]={'0',};//input valables
int i=0,j=0,m;
scanf("%s %s", a, b);
while (a[i] != '\0') {
i++;
}
i--;
while (b[j] != '\0') {
j++;
}
j--;
if(i>j){
m=i;
}else{
m=j;
}
for(int o=0;o<=m;o++){
c.push((int)a[o] - '0');//main problem.convert char to int.
}
for(int o=0;o<=m;o++){
d.push((int)b[o] - '0');
}
int carry=0;//carry varable
for(int o=0;o<=m;o++){
if(c.top()+d.top()+carry>=10){
printf("%d", c.top() + d.top() + carry - 10);
carry=1;
}else{
printf("%d", c.top() + d.top() + carry);
carry=0;
}
c.pop();
d.pop();
}
if (carry > 0) {
printf("%d", carry);
}
}
问题站点: https://codeup.kr/problem.php?id=3021&rid=0 我尝试使用 6 天前学到的堆栈,但在
c.push((int)a[o] - '0');
不起作用。我想要进行大数的加法。
我除了解决这个问题之外。我尝试了-'0'。或者我很困惑。我做了很多可能的事情。
谢谢您的建议。终于我解决了!非常非常感谢您,先生。 这是我的最终代码。我遇到了很多问题,即使我不知道什么是 str len。我想告诉你,谢谢。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
string a, b;
stack<int> c, d;
vector<int> result; // Store the result in a vector.
cin >> a >> b;
for (int o = 0; o < a.length(); o++) {
c.push(a[o] - '0');
}
for (int o = 0; o < b.length(); o++) {
d.push(b[o] - '0');
}
int m = max(a.length(), b.length());
int carry = 0;
for (int o = 0; o < m; o++) {
int digitSum = carry;
if (o < a.length()) {
digitSum += c.top();
c.pop();
}
if (o < b.length()) {
digitSum += d.top();
d.pop();
}
if (digitSum >= 10) {
carry = 1;
digitSum -= 10;
} else {
carry = 0;
}
result.push_back(digitSum); // Store the result in reverse order.
}
if (carry > 0) {
result.push_back(carry);
}
// Print the result in reverse order.
for (int i = result.size() - 1; i >= 0; i--) {
cout << result[i];
}
return 0;
}