课后自主练习(高精度)1074.A-B(Big Integer) easy《编程思维与实践》个人学习笔记

题目

Give two positive integer A and B,calucate A-B.

Notice that A,B is no more than 500 digits.

输入格式
The test case contain several lines.Each line contains two positive integer A and B.

输出格式
For each input line,output a line contain A-B

思路

把A B 拆开放在容器中,然后判断一下谁比较大,A大就A-B正常输出A
B大B-A最后输出B前先输出“-”

代码

#include<iostream>
#include<bits/stdc++.h>


using namespace std;

int main()
{
    string a,b;
    while(cin >> a >> b)
    {
        while(a[0] == '0')
            a.erase(0,1);
        while(b[0] == '0')
            b.erase(0,1);

        deque<int>a1,b1;
        int alen = a.length(), blen = b.length();

        for(int i = 0; i < alen; i++)
            a1.push_back(a[i] - '0');
        for(int i = 0; i < blen; i++)
            b1.push_back(b[i] - '0');

        while(a1.size() < b1.size())//避免越界
            a1.push_front(0);
        while(a1.size() > b1.size())
            b1.push_front(0);


        int same = 1;
        int A = 0, B = 0;
        for(auto ita = a1.begin(), itb = b1.begin(); ita != a1.end() && itb != b1.end(); ita++, itb++)
        {
            if((*ita) != (*itb))
            {
                same = 0;
                if((*ita) > (*itb))
                    A = 1;
                else
                    B = 1;
                break;
            }
        }

        if(same)
            cout <<"0";
        else if(A)
        {
            for(auto ita = a1.rbegin(), itb = b1.rbegin(); ita != a1.rend() && itb != b1.rend(); ita++, itb++)
            {
                *ita -= *itb;
                if(*ita < 0)
                {
                    *ita += 10;
                    *(ita + 1) -= 1;
                }
            }
            while(*a1.begin() == 0)
                a1.pop_front();
            for(auto x : a1)
                cout << x;
            
        }
        else if(B)
        {
            for(auto ita = a1.rbegin(), itb = b1.rbegin(); ita != a1.rend() && itb != b1.rend(); ita++, itb++)
            {
                *itb -= *ita;
                if(*itb < 0)
                {
                    *itb += 10;
                    *(itb + 1) -= 1;
                }
            }
            while(*b1.begin() == 0)
                b1.pop_front();
            cout << "-";
            for(auto x : b1)
                cout << x;
        }
        
        cout << endl;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值