菜鸟的博客

纵有疾风起,人生不言弃。

导航

高精度减法

## A-B

~~~c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;

//判断是否A>=B
bool cmp(vector<int>& A, vector<int>& B)
{
    if (A.size() != B.size()) return A.size() > B.size();//先比较位数
    for (int i = A.size() - 1; i >= 0; i--)
        if (A[i] != B[i])
            return A[i] > B[i];//再一位一位去比较
    return true;
}

vector<int> sub(vector<int>& A, vector<int>& B)
{
    vector<int> C;
    int t = 0;
    for (int i = 0; i < A.size(); i++)
    {
        t = A[i] - t;
        if (i < B.size()) t -= B[i];
        
        C.push_back((t + 10) % 10);//如果t>=0&&t<10,则插入的值为为本身;如果t<0,则插入的数为借位相减后的结果;
                                 
        if (t < 0) t = 1;//若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;
    vector<int> A, B;
    cin >> a >> b;//a = 123456
    for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0');//A = {6.5.4.3.2.1}
    for (int i = b.size() - 1; i >= 0; i--) B.push_back(b[i] - '0');
    if (cmp(A, B))
    {
        auto C = sub(A, B);
        for (int i = C.size() - 1; i >= 0; i--) cout << C[i];
    }
    else
    {
        auto C = sub(B, A);
        printf("-");
        for (int i = C.size() - 1; i >= 0; i--) cout << C[i];
    }

    return 0;
}
~~~

 

posted on 2023-09-20 23:07  hhmzd233  阅读(3)  评论(0编辑  收藏  举报