自己花了几个小时写的
最后边界虽然是对的但是感觉还是很麻烦,等在想想 或找到别人更好的再说吧
#include <iostream>
#include <cstring>
using namespace std;
//字符串反转
void Reverse(char *str)
{
char* left = str;
char temp;
str = str+strlen(str)-1;
while(left < str)
{
temp = *left;
*left++ = *str;
*str-- = temp;
}
}
void Bigsub(char* a,char* b,char* res)
{
int lena = strlen(a),
lenb = strlen(b);
int max = lena >= lenb ? lena : lenb;
int min = lenb;
char *str = new char[max+1];
// 串组a内总是存着二者较长的串组
if(lena < lenb)
{
min = lena;
strcpy(str,a);
strcpy(a,b);
strcpy(b,str);
}
//cout<<a<<endl;
//cout<<b<<endl;
//开始计算
int x = 0,i,sub;
for(i = 0; i < max; i++)
{
if(i < min)
sub = (a[i] - '0') - (b[i] - '0') - x;
else
sub = (a[i] - '0') - x;
//处理a[i] - b[i] < 0的情况,要在前一位接1,
if(sub < 0)
{
res[i] = 10 + sub + '0';
x = 1;
//a[i+1] = a[i+1] - '0' - 1;
}
else
{
res[i] = sub + '0';
x = 0;
}
}
if(res[i-1] == '0')
res[i-1] = 0;
else
res[i] = 0;
}
int main()
{
char a[200],b[200],res[202];
cin>>a>>b;
Reverse(a);
Reverse(b);
Bigsub(a,b,res);
Reverse(res);
cout<<res<<endl;
return 0;
}