Featured image of post [模板]高精度

[模板]高精度

高精度加法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
string add(string a, string b) {
    string res;
    int r = 0;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    int l = max(a.length(), b.length());
    for (int i = 0; i < l; i++) {
        int an = i >= a.length() ? 0 : (a[i] - '0'),
            bn = i >= b.length() ? 0 : (b[i] - '0');
        int cn = (an + bn + r) % 10;
        r = (an + bn + r) / 10;
        res.push_back(cn + '0');
    }
    if (r) res.push_back(r + '0');
    reverse(res.begin(), res.end());
    return res;
}

高精度减法

 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
#include <bits/stdc++.h>
using namespace std;
string sub(string a, string b) {
  if (a == b) return "0";

  bool op = false;
  if (a.length() < b.length()) {
      op = true;
      a.swap(b);
  } else if (a.length() == b.length() && a < b) {
      op = true;
      a.swap(b);
  }

  string res;
  reverse(a.begin(), a.end());
  reverse(b.begin(), b.end());
  int l = max(a.length(), b.length());
  for (int i = 0; i < l; i++) {
    int an = a[i], bn = i >= b.length() ? '0' : b[i];
    if (an < bn) a[i + 1]--, an += 10;
    int cn = an - bn;
    res.push_back(cn + '0');
  }
  while (res[res.length() - 1] == '0') res = res.substr(1, res.length() - 1);
  reverse(res.begin(), res.end());
  return (op ? "-" : "") + res;
}
int main() {
  string a, b;
  cin >> a >> b;
  cout << sub(a, b);
}

高精度乘法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
string mutply(string a, string b) {
    int c[a.length() + b.length() - 1] = {0};
    string res;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    for (int i = 0; i < a.length(); i++)
        for (int j = 0; j < b.length(); j++)
            c[i + j] += (a[i] - '0') * (b[j] - '0');
    for (int i = 0; i < a.length() + b.length() - 1; i++) {
        c[i + 1] += c[i] / 10;
        res.push_back(c[i] % 10 + '0');
    }
    reverse(res.begin(), res.end());
    return res;
}
本站已安全运行
总访问量 次 | 访客 人 | 共 27 篇文章
Built with Hugo
主题 StackJimmy 设计