資源限制
時間限制:1.0s 內存限制:256.0MB
問題描述
高精度減法
輸入格式
兩行,表示兩個非負整數a、b,且有a > b。
輸出格式
一行,表示a與b的差
樣例輸入
1234567890987654321
9999
樣例輸出
1234567890987644322
解題思路:
剛剛完成了高精度乘法,這道高精度減法肯定不是問題,思路一樣,也是先將輸入的字符串轉成int型數組,然後每一位數對應相減,如果小於零,那麼把下一位的數提前減1,以此類推,在最後一位地判斷上尤其需要注意,如果是0,那麼就不輸出,否則也輸出。代碼如下:
#include<bits/stdc++.h>
using namespace std;
const int N = 1000;
int res[N], a[N], b[N];
char sa[N], sb[N];
int main() {
int i, j;
scanf("%s%s",sa,sb);
int lenA = 0, lenB = 0;
for(int i = strlen(sa) - 1; i >= 0; i--) a[lenA ++] = sa[i] - '0';//char型轉成int型
for(int i = strlen(sb) - 1; i >= 0; i--) b[lenB ++] = sb[i] - '0';//char型轉成int型
int index = 0;
for(i = 0, j = 0; i < lenA && j < lenB; i ++, j ++)
{
res[index ++] += a[i] - b[j];
if(res[index - 1] < 0){
res[index - 1] += 10;
res[index] --;
}
}
while(i < lenA){
res[index ++] += a[i];
if(res[index - 1] < 0){
res[index - 1] += 10;
res[index] --;
}
i ++;
}
if(res[index - 1] != 0)
cout << res[index - 1];
for(i = index - 2; i >= 0; i--)
cout << res[i];
return 0;
}