两个大整数相加或相减的问题是很经典的问题。
先输入两个大整数,用string保存,然后转换成自定义的大整数的值。
最后先输出两个数的相加的值,再输出两个数的相减的值。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace std;
typedef struct bignum{
int d[1000];
int len;
bignum(){
fill(d,d+1000,0);
len = 0;
}
}bign;
bign turns(string x){
bign a;
a.len = x.size();
reverse(x.begin(),x.end());
for(int i = 0;i < x.size();i ++){
a.d[i] = x[i] - '0';
}
return a;
}
int cmp(bign a,bign b){//输出为1的话a大,输出-1的话b大,输出0的话相等
if(a.len > b.len) return 1;
if(a.len < b.len) return -1;
for(int i = 0;i < a.len;i ++){
if(a.d[i] > b.d[i]) return 1;
if(a.d[i] < b.d[i]) return -1;
}
return 0;
}
bign add(bign a,bign b){
bign c;
int carry = 0;
for(int i = 0;i < a.len || i < b.len;i ++){
int temp = a.d[i] + b.d[i] + carry;
c.d[c.len ++] = temp % 10;
carry = temp / 10;
}
if(carry != 0)
c.d[c.len ++] = carry;
return c;
}
bign sub(bign a,bign b){
bign c;
for(int i = 0;i < a.len;i ++){
if(a.d[i] < b.d[i]){
a.d[i+1]--;
a.d[i] += 10;
}
c.d[c.len ++] = a.d[i] - b.d[i];
}
while(c.len - 1 > 0 && c.d[c.len-1] == 0)
c.len --;
return c;
}
int main(){
string ss,ss2;
cin >> ss >> ss2;
bign s1 = turns(ss);
bign s2 = turns(ss2);
bign s3 = add(s1,s2);
for(int i = s3.len - 1;i >= 0;i --)
cout << s3.d[i];
cout << endl;
if(cmp(s1,s2) == 1)
s3 = sub(s1,s2);
else if(cmp(s1,s2) == -1){
cout << "-";
s3 = sub(s2,s1);
}
else{
s3.len = 0;
fill(s3.d,s3.d+1000,0);
}
for(int i = s3.len - 1;i >= 0;i --)
cout << s3.d[i];
cout << endl;
return 0;
}
/*
sample input:
99999 1
sample output:
100000
99998
*/