我正在做一个问题,需要我在这里进行大数字的加法,但我无法解决它:
问题描述 Int 是 32 位,long long 是 64 位,不能存储比这更大的数字。编写一个程序来添加两个大数。
输入 输出 在第一行和第二行输入大数a和b。 (a、b为100位以内的整数) 输出大数相加的结果。
输入示例 输出示例 12345678910111213
283928712345678912950500
这是我到目前为止所拥有的:
#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
stack<int> c,d;//stack for adding large numbers
int main(){
char a[100]={'0'};
char b[100]={'0'};//input variables
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 is converting char to int.
}
for (int o=0;o<=m;o++) {
d.push((int)b[o] - '0');
}
int carry=0;//carry variable
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);
}
return 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;
}