P2142. 高精度减法

考点

  • 高精度

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>

using namespace std;

const int LEN = 25000;

class BigInt
{
public:
int len_;
int arr_[LEN];
int &operator[](int idx)
{
return arr_[idx];
}
BigInt(string s = "")
{
memset(arr_, 0, sizeof(arr_));
len_ = s.length();
for (int i = 1; i <= len_; ++i)
{
arr_[i] = s[len_ - i] - '0';
}
}
void flatten(int len)
{
len_ = len;
for (int i = 1; i <= len_; ++i)
{
if (arr_[i] < 0)
{
arr_[i + 1] -= 1;
arr_[i] += 10;
}
}
while (!arr_[len_])
--len_;
}
void print()
{
for (int i = max(1, len_); i >= 1; --i)
{
cout << arr_[i];
}
}
};

//lst_dg代表当前a的最低有效位
bool greater_eq(BigInt a, int lst_dg, BigInt b)
{
//a的位数比b的位数少
if (a.len_ < b.len_)
return false;
if (a.len_ > b.len_)
return true;
for (int i = b.len_ - 1; i >= 0; --i)
{
if (a[lst_dg + i] > b[i + 1])
return true;
if (a[lst_dg + i] < b[i + 1])
return false;
}
//a和b的值相等
return true;
}

BigInt operator-(BigInt a, BigInt b)
{
BigInt c;
int len = a.len_;
for (int i = 1; i <= len; ++i)
{
c[i] += a[i] - b[i];
}
c.flatten(len);
return c;
}

int main()
{
string s1, s2;
cin >> s1 >> s2;
BigInt a(s1), b(s2);
if (!greater_eq(a, 1, b))
{
cout << "-";
(b - a).print();
}
else
{
(a - b).print();
}
return 0;
}

思路

与高精度加法、乘法唯一不同的是,需要新增一个greater_eq函数来确保参数a是大于等于参数b

greater_eq函数的功能较简单,执行流程如下:

  • 比较ab的长度大小
  • ab的长度相等,则从高位向低位逐个比较

该函数的参数lst_dg在高精度减法中暂无作用,但在高精度除法中是关键;下述函数内的代码块

1
2
if (a.len_ > b.len_)
return true;

在高精度除法中将会被替换成这样:

1
2
if (a[lst_dg + b.len_] != 0)
return true;

看似效果一样,但两者不可混用!!!!!

在高精度减法中,用a[lst_dg + b.len_]来判断a大于b是绝对错误的!

比如a的值为1001,与b的值为1进行比较,上述代码块就不会返回true

而在高精度除法中,该代码段判断以lst_dg为最低有效位的a是否大于等于b是可以的

高精度运算的数组都是倒序放置,且高精度除法是从高位开始运算,而加减乘法是从低位开始运算

所以被除数的某位为0,那么比它更高的位次也一定为0