321
社区成员




大数一直是一个c语言的一个难题。 现在我们需要你手动模拟出大数加法过程。 请你给出两个大整数加法结果。
是不是不用 c++ 这个题目就没啥意义了?
print(int(input())+int(input()))
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char a1[MAXLEN];
char a2[MAXLEN];
static int v1[MAXLEN];
static int v2[MAXLEN];
static int v3[MAXLEN];
int i,j,n,L,z;
void main(void) {
scanf("%d",&n);
for (j=0;j<n;j++) {
scanf("%s%s",a1,a2);
L=strlen(a1);
for (i=0;i<L;i++) v1[i]=a1[L-1-i]-'0';
L=strlen(a2);
for (i=0;i<L;i++) v2[i]=a2[L-1-i]-'0';
for (i=0;i<MAXLEN;i++) v3[i]=v1[i]+v2[i];
for (i=0;i<MAXLEN;i++) {
if (v3[i]>=10) {
v3[i+1]+=v3[i]/10;
v3[i]=v3[i]%10;
}
}
printf("Case %d:\n", j+1);
printf("%s + %s = ", a1, a2);
z=0;
for (i=MAXLEN-1;i>=0;i--) {
if (z==0) {
if (v3[i]!=0) {
printf("%d",v3[i]);
z=1;
}
} else {
printf("%d",v3[i]);
}
}
if (z==0) printf("0");
printf("\n");
}
}
//Sample Input
//3
//0 0
//1 2
//112233445566778899 998877665544332211
//
//Sample Output
//Case 1:
//0 + 0 = 0
//Case 2:
//1 + 2 = 3
//Case 3:
//112233445566778899 + 998877665544332211 = 1111111111111111110
之前写过一个c++的大数模板...不过加减只能处理同号的情况....
class BigInteger {
private:
string __version__ = "1.0";
int d[MAX]; // 左对齐存储数字, d[0]存储大数字的最低位, d[MAX-1]存储最高位
int len;
bool positive; // 正负
public:
BigInteger(); // 无参构造
BigInteger(string str); // 有参构造, 返回字符串对应的大整数, 字符串第一位为符号位, +省略
int getLength(); // 整数长度, 不包括符号位
bool isPositive(); // 是否为正
string getVersion();
string toString(bool withFlag); // withFlag表示是否返回符号位
// 重载五种基本比较
bool operator < (const BigInteger& bint)const;
bool operator > (const BigInteger& bint)const;
bool operator == (const BigInteger& bint)const;
bool operator >= (const BigInteger& bint)const;
bool operator <= (const BigInteger& bint)const;
// 重载输出格式
friend ostream& operator<< (ostream& out, const BigInteger& bint);
// 大整数之间的运算
BigInteger operator+(BigInteger& bint);
BigInteger operator-(BigInteger& bint);
BigInteger operator*(BigInteger& bint);
BigInteger operator/(BigInteger& bint);
BigInteger operator%(BigInteger& bint);
void operator+=(BigInteger& bint);
void operator-=(BigInteger& bint);
void operator*=(BigInteger& bint);
void operator%=(BigInteger& bint);
};
BigInteger BigInteger::operator+(BigInteger& bint) {
assert(this->positive == bint.positive);
BigInteger result;
result.positive = this->positive;
int carry = 0; // 进位
for (int i = 0; i < this->len || i < bint.len; i++) {
int temp = this->d[i] + bint.d[i] + carry;
result.d[result.len++] = temp % 10;
carry = temp / 10;
}
if (carry != 0) result.d[result.len++] = carry;
return result;
}