View Code
#include<iostream>
using namespace std;
char a[1001] ;
char x_a[1001] , y_b[1001] ;
char xx[1001] , yy[1001];
char x1[1001] , y1[1001];
int Lx , Ly ;
int sum[1001] ;
int num ;
int sign=0;
int mark_x , mark_y ;
int x[1001],y[1001];
void Init_A() //将字符转化为数字
{
int i;
for ( i = 0 ; i < Lx ; i++ ) x[i] = x_a[i] - '0' ;
for( i = 0 ; i < Ly ; i++ ) y[i] = y_b[i] - '0' ;
}
void Init_S()
{
int i;
for ( i = 0 ; i < Lx ; i++ ) x1[Lx-i-1] = x_a[i] ;
for( i = 0 ; i < Ly ; i++ ) y1[Ly-i-1] = y_b[i];
strcpy(x_a , x1);
strcpy(y_b , y1);
Init_A();
}
void Change() //交换x,y,如果x<y;
{
strcpy( a , y_b) ;
strcpy( y_b , x_a ) ;
strcpy( x_a , a ) ;
int temp = Lx ;
Lx = Ly ;
Ly = temp;
}
void Cmp( ) //保证x>=y
{
int i;
if(Lx < Ly) { sign=1; Change();}
if(Lx==Ly)
{
for( i = 0 ; i < Lx ; i++ )
if(x_a[i]<y_b[i]) break;
if( i != Lx )
{
sign=1;
Change();
}
}
}
void Add() //高精度加法
{
num=0;
int i , j , flag=0;
for( i = Lx ,j = Ly ; i >= Lx - Ly , j >= 0; i-- , j--)
{
sum[num++] = ( x[i] + y[j] + flag)%10;
flag = ( x[i] + y[j] + flag)/10;
}
for(i = Lx - Ly - 1 ; i >= 0; i--)
{
sum[num++] = ( x[i] + flag )%10;
flag = ( x[i] + flag )/10;
}
while(flag)
{
sum[num++] = flag%10;
flag /= 10;
}
}
void Sub() //高精度减法
{
num=0;
int i ;
for(i=0;i < Lx; i++)
{
sum[i]+=x[i]-y[i];
if(sum[i]<0)
{
sum[i+1]--;
sum[i]+=10;
}
}
while( Lx > 1 && sum[Lx-1]==0) Lx--;
num = Lx;
}
void PrintAdd()
{
int i;
for(i = num-1 ;i >0 ;i--)
printf("%d",sum[i]);
}
void PrintSub()
{
int i;
for(i = num-1 ;i >=0 ; i--)
printf("%d",sum[i]);
}
int main()
{
while(scanf("%s%s",xx, yy)!=EOF)
{
int L1 = strlen(xx);
int L2 = strlen(yy);
num=0; sign=0;
memset( sum , 0 , sizeof(sum));
memset( x , 0 , sizeof(x));
memset( y , 0 , sizeof(y));
memset( x_a , 0 , sizeof(x_a));
memset( y_b , 0 , sizeof(y_b));
memset( x1 , 0 , sizeof(x1));
memset( y1 , 0 , sizeof(y1));
mark_x = mark_y = 0 ;
Lx=L1;
Ly=L2;
int i;
if( xx[0] == '-' || xx[0] == '+' )
{
if(xx[0] == '-' ) mark_x = 1;
for( i = 1 ; i < Lx ; i++ ) x_a[i-1] = xx[i];
Lx = Lx-1;
}
if(xx[0]!='-' && xx[0]!='+')
{
for(i=0;i<Lx;i++) x_a[i]=xx[i];
}
if(yy[0] == '-' || yy[0] == '+' )
{
if(yy[0] == '-') mark_y = 1;
for(i = 1 ; i < Ly ; i++ ) y_b[i-1] = yy[i];
Ly = Ly-1;
}
if(yy[0]!='-' && yy[0]!='+') for(i=0;i<Ly;i++) y_b[i] = yy[i];
if(mark_x == 0 )
{
if( mark_y == 0)
{
Cmp();
Init_S();
Sub();
if(sign==1) printf("-");
PrintSub();
}
if(mark_y == 1)
{
Cmp();
Init_A();
Add();
PrintAdd();
}
}
if(mark_x == 1)
{
if( mark_y == 0)
{
Cmp();
Init_A ();
Add();
printf("-");
PrintAdd();
}
if(mark_y == 1)
{
Cmp();
Init_S();
Sub();
if(sign==0) printf("-");
PrintSub();
}
}
printf("\n");
}
return 0;
}