天天看點

Codevs 3115 高精度練習之減法

題目描述 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<cstring>
using namespace std;


int Substraction (int c[], int length1, int d[], int length2, int e[])
{
int i=0, ans=0;
while(i <= length1-1 || i <= length2-1)//兩個數都沒有到底
{
e[i] = c[i] - d[i] - ans;
if(e[i] < 0)
{
ans = 1;
e[i] = e[i] + 10;//判斷借位
}
else
{
ans = 0;
}
i++;
}
return i-1;
}


int main()
{
char a[500],b[500];
int c[500],d[500],e[500];
int length1, length2, length3;
int i;
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
memset(e,0,sizeof(e)); 
cin>>a;
cin>>b; 
length1 = strlen(a);
length2 = strlen(b); 
for (i = 0; i <= length1-1; i++ ) 
{
c[length1 - i - 1] = a[i] - 48; 
}
for (i = 0; i <= length2-1; i++ ) 
{
d[length2 - i - 1] = b[i] - 48;//轉換成int型
}
int flag = 0;
if(length1 > length2 || length1 == length2 && strcmp(a,b) >= 0)
{
length3 = Substraction(c, length1, d, length2, e);
for (i = length3; i >= 0; i--) 
{
if(e[i]&&!flag)
{
flag = 1;
cout<< e[i];
}
else if(flag)
{
cout<< e[i];
}
}
if(!flag)
cout<<0;
cout<< endl;
return 0; 
}
else
{
cout <<"-";
length3 = Substraction(d, length2,c, length1, e);
for (i = length3; i >= 0; i--) 
{
if(e[i]&&!flag)
{
flag = 1;
cout<< e[i];
}
else if(flag)
{
cout<<e[i];
}
}
cout<< endl;
return 0; 
} 
}
           

繼續閱讀