Precision "-" algorithm

A high-precision "-" algorithm

1.1 preparation of high-precision "-", remember the following, the code will be getting!

(1) Firstly, high-precision "+" same approach to store large integers

(2) followed by storage end, consider how operation?

Second, high-precision "-" core algorithm

2.1 large integer storage

• Whether it is written '+' '-' '*' '/' which must be guaranteed the same large integer storage format, because very often there is not only a symbol of operation.

2.2 subtraction of nature

• large integer subtraction: C = A3A2A1A0-B2B1B0, two cases should be considered, if Ai-Bi-t Save enough, the final median Ai-Bi-t, if not reduced, compared to the final digit Ai-Bi-t + 10, in fact, in both cases (t + 10)% 10 is.

2.3 In addition, we want to know

(1) learn to judge the size of two large integers in the array, the median is generally different, longer length that will be bigger, if the same number of bits, from the highest bit comparison, which is the last bit of the array .

(2) if A is greater than equal to B -> Direct operator, or -> - (BA).

(3) the situation may occur leading zeros removed!

(4) Processing Here two positive integers, if negative integer, will be able to convert bit | A | + | B | or | A | - | B |.

Third, high-precision "-" code templates

Add a comment

"""
bool cmp(vector<int> &A,vector<int> &B)//判断A是否大于等于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;
}
"""
}
// C = A - B, 满足A >= B, A >= 0, B >= 0
vector<int> sub(vector<int> &A, vector<int> &B)
{
    vector<int> C;
    for (int i = 0, t = 0; i < A.size(); i ++ )
    {
        t = A[i] - t;
        if (i < B.size()) t -= B[i];
        C.push_back((t + 10) % 10);//分两种情况考虑,如果Ai-Bi-t够减,则最终的位数为Ai-Bi-t,如果不够减,最终的位数则为Ai-Bi-t+10
        if (t < 0) t = 1;
        else t = 0;
    }

    while (C.size() > 1 && C.back() == 0) C.pop_back();//去掉前导零
    return C;
}

作者:yxc
链接:https://www.acwing.com/problem/content/794/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin www.cnblogs.com/lastk/p/12443379.html