题解 | #A+B# 高精度加减,注意范围,写复杂了

A+B

https://www.nowcoder.com/practice/b183eac8dfba4de99d47c1ca4ce9571f

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

string s1, s2;

vector<int> add(vector<int> &a, vector<int> &b)
{
    if(a.size() < b.size()) return add(b, a);
    vector<int> c;
    int t = 0;
    for(int i = 0; i < a.size(); i++)
    {
        t += a[i];
        if(i < b.size()) t += b[i];
        c.push_back(t % 10);
        t /= 10;
    }
    if(t) c.push_back(1);
    return c;
}

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);
        if(t < 0) t = 1;
        else t = 0;
    }
    while(c.size() > 1 && c.back() == 0) c.pop_back();
    return c;
}

int main() {
    while(cin >> s1 >> s2)
    {
        string tmp1, tmp2;
        vector<int> v1, v2;
        vector<int> res;
        for(int i = 0; i < s1.size(); i++)
            if(s1[i] != ',') tmp1 += s1[i];

        for(int i = 0; i < s2.size(); i++)
            if(s2[i] != ',') tmp2 += s2[i];   

        for(int i = tmp1.size()-1; i >= 0; i--)
            if(tmp1[i] >= '0' && tmp1[i] <= '9')
                v1.push_back(tmp1[i] - '0');
        for(int i = tmp2.size()-1; i >= 0; i--)
            if(tmp2[i] >= '0' && tmp2[i] <= '9')
                v2.push_back(tmp2[i] - '0');
        if(tmp1[0] != '-' && tmp2[0] != '-')
        {
            res = add(v1, v2);
        } 
        else if(tmp1[0] == '-' && tmp2[0] == '-')
        {
            res = add(v1, v2);
            cout << "-";
        }
        else if(tmp1[0] == '-' && tmp2[0] != '-')
        {
            if(cmp(v1, v2))
            {
                res = sub(v1, v2);
                cout << "-";
            }
            else 
            {
                res = sub(v2, v1);
            }
        }
        else 
        {
            if(cmp(v1, v2))
            {
                res = sub(v1, v2);
            }
            else 
            {
                res = sub(v2, v1);
                cout << "-";
            }
        }
        for(int i = res.size()-1; i >= 0; i--) cout << res[i];
        cout << endl;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务