- 分享
2023-12-27 高精度减法 A = B 问题
- 2023-12-28 8:40:42 @
A = B 时:A - B = -0 问题
由于 cmp 函数里没有判断 A = B 的情况,需增加 A = B 时返回 true
的情况。
另 size()
函数返回值为无符号整数 unsigned
,当 size() == 0
,再减 1,会导致溢出,从而使数据变大。
例如:
int main()
{
vector<int> arr;
cout<<arr.size()<<endl; // 输出 0
cout<<arr.size() - 1<<endl; // 输出 429496729
}
所以建议统一写 (signed)size() - 1
转化为有符号整数
高精度减法完整代码如下:
#include <bits/stdc++.h>
using namespace std;
bool cmp(vector<int> &A, vector<int> &B)
{
if(A.size() != B.size()) return A.size() > B.size();
for (int i = (signed)A.size() - 1; i >= 0; i -- )
if (A[i] != B[i])
return A[i] > B[i];
return true; // A = B 时返回真
}
vector<int> sub(vector<int> &A, vector<int> &B)
{
vector<int> C;
for (int i = 0, t = 0; i < A.size(); i ++ )
{
t = A[i] - t;
if (i < B.size()) t -= B[i];
C.push_back((t + 10) % 10);
if(t < 0) t = 1;
else t = 0;
}
while (C.size() > 1 && C.back() == 0) C.pop_back(); // 去除前导0
return C;
}
int main()
{
string a, b;
cin >> a >> b;
vector<int> A, B;
for (int i = (signed)a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
for (int i = (signed)b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
vector<int> C;
if(cmp(A, B)) C = sub(A, B);
else C = sub(B, A), cout << '-';
for (int i = (signed)C.size() - 1; i >= 0; i -- ) cout << C[i];
cout << endl;
return 0;
}
0 comments
No comments so far...