描述:
给定两个大数字符串A和B,计算A-B的值
运行时间限制: 无限制
内存限制: 无限制
输入:
两个以空格分隔的数字字符串,数字由0~9构成,输入字符串最长为100个字符。
输出:
输出两个数字字符串相减以后的结果,如果为负,需要在输出的数字前面添加"-"
#include<iostream>
#include<stdlib.h>
using namespace std;
bool comp(char* s1,char* s2){
if (strlen(s1) >= strlen(s2))
return true;
else
return false;
}
int main(){
char* s1;
s1 = (char*)malloc(100 * sizeof(char*));
char* s2;
s2 = (char*)malloc(100 * sizeof(char*));
cin >> s1;
cin >> s2;
if (comp(s1, s2)){
int* ans;
ans = (int*)malloc(100*sizeof(int*));
int lang1 = strlen(s1);
int lang2 = strlen(s2);
int i = 0,j=0;
for (i = lang1-1,j=lang2-1; i >=lang1-lang2; i--,j--){
if (s1[i] >= s2[j]){
ans[i] = s1[i] - s2[j];
}
else{
ans[i] = s1[i] + 10 - s2[j];
s1[i - 1] = s1[i -1] - 1;
}
}//end for
for (int ii = 0; ii < lang1-lang2; ii++){
ans[ii] = s1[ii]-48;
}
for (int iii = 0; iii < lang1; iii++){
cout << ans[iii];
}
}//end cmp;
else{
char* tmp;
tmp = (char*)malloc(100 * sizeof(char*));
tmp = s1;
s1 = s2;
s2 = tmp;
int* ans;
ans = (int*)malloc(100 * sizeof(int*));
int lang1 = strlen(s1);
int lang2 = strlen(s2);
int i = 0, j = 0;
for (i = lang1 - 1, j = lang2 - 1; i >= lang1 - lang2; i--, j--){
if (s1[i] >= s2[j]){
ans[i] = s1[i] - s2[j];
}
else{
ans[i] = s1[i] + 10 - s2[j];
s1[i - 1] = s1[i - 1] - 1;
}
}//end for
for (int ii = 0; ii < lang1 - lang2; ii++){
ans[ii] = s1[ii] - 48;
}
cout << "-";
for (int iii = 0; iii < lang1; iii++){
cout <<ans[iii];
}
}
<span style="font-family: Helvetica, Tahoma, Arial, sans-serif;">}</span>