题解 | #A+B#
A+B
https://www.nowcoder.com/practice/b183eac8dfba4de99d47c1ca4ce9571f
#include <iostream>
using namespace std;
struct bign {
int data[10] ;
int len;
int fuhao;
bign() {
len = 0;
fuhao = 0;
for (int i = 0; i < 10; ++i) {
data[i] = 0;
}
}
};
bign to_b(string str) {
int len = str.length();
bign b1;
for (int i = 0; i < len; i++) {
if (str[len - i - 1] >= '0' && str[len - i - 1] <= '9') {
b1.data[b1.len++] = str[len - i - 1] - '0';
}
}
if (str[0] == '-') b1.fuhao = 1;
return b1;
}
bign add_b(bign b1, bign b2) {
int carry = 0;
bign b3;
for (int i = 0; i < b1.len || i < b2.len; i++) {
int a = b1.data[i] + b2.data[i] + carry;
b3.data[b3.len++] = a % 10;
carry = a / 10;
}
if (carry != 0) {
b3.data[b3.len++] = carry;
}
return b3;
}
bool cmp(bign b1, bign b2) {//b1>b2为真
if(b1.len<b2.len){
return false;
}
if(b1.len==b2.len){
for(int i=b1.len-1;i>=0;i--){
if(b1.data[i]>b2.data[i]){
return true;
}else if(b1.data[i]<b2.data[i])
{
return false;
}
}
}
return true;
}
bign sub_b(bign b1,bign b2){
int carry=0;
bign b3;
for(int i=0;i<b1.len||i<b2.len;i++){
int a=b1.data[i]-b2.data[i]-carry;
if(a<0){
carry=1;
b3.data[b3.len++]=a+10;//不要忘了修改长度
}else{
b3.data[b3.len++]=a;
carry = 0;
}
}
while(b3.data[b3.len-1]==0){
b3.len--;
}
return b3;
}
int main() {
string str1, str2;
while (cin >> str1 >> str2) { // 注意 while 处理多个 case
bign b1 = to_b(str1);
bign b2 = to_b(str2);
bign b3;
if (b1.fuhao == 1 && b2.fuhao == 1) {
b3 = add_b(b1, b2);
cout << "-";
} else if (b1.fuhao == 0 && b2.fuhao == 0) {
b3 = add_b(b1, b2);
} else if (b1.fuhao == 1 && b2.fuhao == 0) {
bool dx = cmp(b1, b2);
if (dx) { //dxtrue表示b1>b2,shuchufuhao
cout << "-";
b3 = sub_b(b1, b2);
} else {
b3 = sub_b(b2, b1);
}
} else {
bool dx = cmp(b2, b1);
if (dx) { //dxtrue表示b2>b1,shuchufuhao
cout << "-";
b3 = sub_b(b2, b1);
} else {
b3 = sub_b(b1, b2);
}
}
for (int i = b3.len - 1; i >= 0; i--) {
cout << b3.data[i];
}
cout<<endl;
}
}
// 64 位输出请用 printf("%lld")
哭了,改了好多遍终于对了!!