abel_abel
2021-02-09 08:57:50
高精度加法和减法模板
数学课做减法
// 数学课做减法.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
using VI = vector<int>;
bool cmp(VI& a, VI& b) {
if (a.size() != b.size()) return a.size() > b.size();
for (size_t i = 0; i < a.size(); ++i)
if (a[i] != b[i]) return a[i] > b[i];
return true;
}
VI sub(VI& a, VI& b) {
VI c;
for (int i = 0, t = 0; i < int(a.size()); ++i) {
t = a[i] - t;
if (i < b.size()) t -= b[i];
c.push_back((t + 10) % 10);
t = t < 0;
}
while (c.size() > 1 && !c.back()) c.pop_back();
return c;
}
VI add(VI& a, VI& b) {
VI c;
int t = 0;
for (int i = 0; i < int(a.size()) || i < int(b.size()); ++i) {
if (i < a.size()) t += a[i];
if (i < b.size()) t += b[i];
c.push_back(t % 10);
t /= 10;
}
if (t) c.push_back(t);
return c;
}
void print(VI& c) {
int j = 0;
for (int i = c.size() - 1; i >= 0; --i, ++j) {
if ((c.size() - j) % 3 == 0) printf(",");
printf("%d", c[i]);
}
puts("");
}
void psub(VI& A, VI& B) {
VI C;
if (cmp(A, B)) {
C = sub(A, B);
}
else {
printf("-");
C = sub(B, A);
}
print(C);
}
int main()
{
#ifdef _DEBUG
#pragma warning(disable: 4996)
freopen("in.txt", "r", stdin);
#endif // _DEBUG
string a, b;
cin >> a >> b;
int sa = 1, sb = 1;
VI A, B, C;
for (int i = int(a.size()) - 1; i >= 0; --i)
if (a[i] != '-') A.push_back(a[i] - '0');
else sa = -1;
for (int i = int(b.size()) - 1; i >= 0; --i)
if (b[i] != '-') B.push_back(b[i] - '0');
else sb = -1;
if (sa == 1 && sb == 1) {
psub(A, B);
}
else if (sa == -1 && sb == -1) {
psub(B, A);
}
else if (sa == 1 && sb == -1) {
C = add(A, B);
print(C);
}
else if (sa == -1 && sb == 1) {
C = add(A, B);
printf("-");
print(C);
}
return 0;
}
另外一道模板题: P2142 高精度减法
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
using VI = vector<int>;
bool cmp(VI& a, VI& b) {
int n = a.size(), m = b.size();
if (n != m) return n > m;
for (int i = n - 1; i >= 0; --i)
if (a[i] != b[i]) return a[i] > b[i];
return true;
}
VI Sub(VI& a, VI& b) {
VI c;
int t = 0, n = a.size(), m = b.size();
for (int i = 0; i < n; ++i) {
t = a[i] - t;
if (i < m) t -= b[i];
c.push_back((t + 10) % 10);
t = t < 0;
}
while (c.size() > 1 && !c.back()) c.pop_back();
return c;
}
int main() {
#ifdef _DEBUG
freopen("Sub.in", "r", stdin);
#endif
string a, b;
cin >> a >> b;
VI A, B, C;
for (int i = a.size() - 1; i >= 0; --i) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; --i) B.push_back(b[i] - '0');
if (cmp(A, B))
C = Sub(A, B);
else {
printf("-");
C = Sub(B, A);
}
for (int i = C.size() - 1; i >= 0; --i) printf("%d", C[i]);
puts("");
return 0;
}