(Precision) of large numbers subtraction in C ++

Foreword

Two days in the brush algorithm problem, which involves a high-precision arithmetic, since I use C ++, so it is necessary to manually Simulation. Using java and python students can not worry, Java has a BigDecimal class can implement, python can be implemented directly.

Well, let's directly on the code, the code has a corresponding comment, I believe you can read it.

Code

#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;

//比较两个数的大小
bool checkSize(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 true;
            break;
        }
        if(A[i]<B[i])
        {
            return false;
            break;
        }
    }
    return true;
}

//加法
vector<int> add(vector<int> &A,vector<int> &B)
{
    vector<int> C;
    int t=0;
    for(int i=0;i<A.size()|| i<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!=0) C.push_back(1);
    return C;
}

//减法
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);
        if(t<0) t=1;
        else t=0;
    }
    //去除前导0
    while(C.size()>1 && C.back()==0) C.pop_back();
    return C;
}

int main()
{
    string a,b,op;
    vector<int> A,B;
    cin >> a >> op >>b;
    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(op=="add")
    {
        vector<int> C = add(A,B);
        for(int i=C.size()-1;i>=0;i--) printf("%d",C[i]);
    }
    if(op=="sub")
    {
        vector<int> C;
        if(checkSize(A,B))
        {
            C= sub(A,B);
            for(int i=C.size()-1;i>=0;i--) printf("%d",C[i]);
        }
        else
        {
            C = sub(B,A);
            cout << "-";
            for(int i=C.size()-1;i>=0;i--) printf("%d",C[i]);
        }
    }
    return 0;
}

More you can visit my personal blog: a much blame

Guess you like

Origin www.cnblogs.com/cydi/p/12468400.html