高精度算法

2019-12-06

大家都有过高精度类型的经历,比如让你算 A+B 的答案,正常人肯定就是认为就直接 A+B 了,但是如果 A,B 的范围都超过了 long long 的范围。那么 C++肯定是用long long算不出来的,所以我们要进行字符串的模拟

A+B $(A,B>=0)$

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string a, string b)
{
    int hex = 0;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    int len1 = a.length();
    int len2 = b.length();
    string ans;
    for (int i = 0, j = 0; i < len1 || j < len2; i++, j++)
    {
        int num1 = 0, num2 = 0;
        if (i < len1)
            num1 = a[i] - '0';
        if (j < len2)
            num2 = b[i] - '0';
        ans = char((num1 + num2 + hex) % 10 + '0') + ans;
        hex = (num1 + num2 + hex) / 10;
    }
    if (hex)
        ans = char(hex + '0') + ans;
    return ans;
}
int main()
{
    string a, b;
    while (cin >> a >> b)
        cout << add(a, b) << endl;
}

A*B $(A,B>=0)$

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string mult(string a, string b)
{
    string ans;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    int len1 = a.length(), len2 = b.length(), result[len1 + len2] = {0};
    for (int i = 0; i < len1; i++)
        for (int j = 0; j < len2; j++)
            result[i + j] += (a[i] - '0') * (b[j] - '0');
    for (int i = 0; i < len1 + len2 - 1; i++)
    {
        result[i + 1] += result[i] / 10;
        result[i] %= 10;
    }
    int i = len1 + len2 - 1;
    while (result[i] == 0 && i > 0)
        i--;
    for (; i >= 0; i--)
        ans += char(result[i] + '0');
    return ans;
}
int main()
{
    string a, b;
    while (cin >> a >> b)
        cout << mult(a, b) << endl;
}

A-B $(A,B>=0)$

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string sub(string a, string b)
{
    int len1 = a.length(), len2 = b.length(), result[max(len1, len2)]{0}; //假设a是最大的,b是最小的
    bool flag = false;
    string ans;
    if (len1 < len2)
        swap(a, b), swap(len1, len2), flag = true;
    else if (len1 == len2)
    {
        int i;
        for (i = 0; i < len1 && a[i] == b[i]; i++);
        if (a[i] < b[i])
            swap(a, b), flag = true;
    }
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    int i;
    for (i = 0; i < len2; i++)
        if (a[i] >= b[i])
            result[i] = a[i] - b[i];
        else
            result[i] = a[i] + 10 - b[i], a[i + 1] -= 1;

    while (i < len1)
        result[i] = a[i] - '0', i++;

    for (i = len1 - 1; i > 0; i--)
        if (result[i] == 0)
            len1--;
        else
            break;

    for (i = 0; i < len1; i++)
        ans = char(result[i] + '0') + ans;

    if (flag)
        ans = "-" + ans;

    return ans;
}
int main()
{
    string a, b;
    while (cin >> a >> b)
        cout << sub(a, b) << endl;
}

如果整合有需要,我贴一个链接
C++整合代码
C 整合代码

算法

IT创新实验室19级阶段性测试一

多喝嘤料