题目描述 Description
给出两个正整数A和B,计算A-B的值。保证A和B的位数不超过500位。
输入描述 Input Description
读入两个用空格隔开的正整数
输出描述 Output Description
输出A-B的值
样例输入 Sample Input
3 12
样例输出 Sample Output
-9
数据范围及提示 Data Size & Hint
两个正整数的位数不超过500位
按位减就可以了,我搞了几个函数,所以代码长了一点
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[510],b[510],ans[510];
bool t; int now=0;
void swap() {
int l1=strlen(a),l2=strlen(b);char c;
for(int i=0;i<max(l1,l2);i++) {
c=a[i];a[i]=b[i];b[i]=c;
} return;
}
void check() {
int l1=strlen(a),l2=strlen(b);
if(l1<l2) {
swap();t=true;return;
}
else if(l1==l2) {
for(int i=0;i<l1;i++) {
if(a[i]>b[i]) { t=false;return; }
if(a[i]<b[i]) { swap();t=true;return; }
}
}
t=false;return;
}
void minus0() {
int l1=strlen(a),l2=strlen(b);int r=0;
for(int i=l1-1,j=l2-1;i>=0||j>=0;i--,j--) {
ans[++now]='0'-r;r=0;
if(i>=0) ans[now]+=(a[i]-'0');
if(j>=0) ans[now]-=(b[j]-'0');
if(ans[now]<'0') {
r=1;ans[now]+=10;
}
} return;
}
int main() {
scanf("%s%s",a,b);
check();minus0();
if(t) printf("-");
while(ans[now]=='0'&&now>1) now--;
for(int i=now;i>0;i--) {
printf("%c",ans[i]);
}
}