题目
?
题目链接:ZOJ1001 A + B Problemhttps://zoj.pintia.cn/problem-sets/91827364500/problems/91827364500
测试样例
输入样例1(题目给的)
1 5
输出样例1
6
输入样例2(自编,A>0 && B>0 && A>LL_MAX && B>LL_MAX)
1234567898765432123456789 9876543212345678987654321
输出样例2
11111111111111111111111110
输入样例3(自编,A>0 && B<0 && A>LL_MAX && -B>LL_MAX)
66666666666666666666666666666 -88888888888888888888888888
输出样例3
66577777777777777777777777778
输入样例3(自编,A<0 && B>0 && -A>LL_MAX && B>LL_MAX)
-111111111111111111111111111222222 1111111111111111111111111222222
输出样例3
-110000000000000000000000000000000
?
输入样例4(自编,A<0 && B<0 && -A>LL_MAX && -B>LL_MAX)
-19824789237842398542385785234858724875 -89314723894728937429897398
输出样例4
-19824789237931713266280514172288622273
输入样例5(自编,A<0 && B>0 && A>LL_MAX && B>LL_MAX && A+B = 0)
-88888888888888888888888888888888888888888888888
88888888888888888888888888888888888888888888888
输出样例5
0
提交结果截图
?
带详细注释的源代码
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
//大整数加法
string sum(string a, string b)
{
string res;
int a_len = a.length(), b_len = b.length();
if (a_len >= b_len)
res = a;
else
res = b;
int carry_bit = 0;//进位
int k = max(a_len, b_len) - 1;
for (int i = a_len - 1, j = b_len - 1; i >= 0 && j >= 0; i--, j--, k--)
{
res[k] = a[i] + b[j] - '0' + carry_bit;
carry_bit = 0;
while (res[k] > '9')
{
res[k] -= 10;
carry_bit++;
}
}
while (carry_bit)
{
if (k == -1 && carry_bit)
{
res = '0' + res;
res[0] += carry_bit;
break;
}
res[k] = res[k] + carry_bit;
carry_bit = 0;
while (res[k] > '9')
{
res[k] -= 10;
carry_bit++;
}
k--;
}
return res;
}
//大整数减法
string sub(string a, string b)
{
string res;
bool can_flag = true;//a-b是否够减
int a_len = a.length(), b_len = b.length();
if (!((a_len > b_len || (a_len == b_len && a > b))))
{
can_flag = false;
swap(a, b);
a_len = a.length(), b_len = b.length();//更新长度
}
res = a;
int borrow_bit = 0;//借位
int k = a_len - 1;
for (int i = a_len - 1, j = b_len - 1; i >= 0 && j >= 0; i--, j--, k--)
{
res[k] = a[i] - b[j] - borrow_bit + '0';
borrow_bit = 0;
while (res[k] < '0')
{
res[k] += 10;
borrow_bit++;
}
}
while (borrow_bit)
{
res[k] = res[k] - borrow_bit;
borrow_bit = 0;
while (res[k] < '0')
{
res[k] -= 10;
borrow_bit++;
}
k--;
}
while (res[0] == '0' && res.length() != 1)
res = res.substr(1, res.length());
if (!can_flag && res[0] != '0')
res = '-' + res;
return res;
}
int main()
{
string a, b, res;
while (cin >> a >> b)
{
if (a[0] != '-' && b[0] != '-')
res = sum(a, b);
else if (a[0] != '-' && b[0] == '-')
{
b = b.substr(1, b.length());//去除负号
res = sub(a, b);
}
else if (a[0] == '-' && b[0] != '-')
{
swap(a, b);
b = b.substr(1, b.length());//去除负号
res = sub(a, b);
}
else if (a[0] == '-' && b[0] == '-')
{
a = a.substr(1, a.length());//去除负号
b = b.substr(1, b.length());//去除负号
res = sum(a, b);
if (res[0] != '0')
res = '-' + res;
}
cout << res << endl;
}
return 0;
};
|