超大整数的和,基本功修炼

最近在网上看到个求两个超大整数的和,如果用整数int表示的话,肯定会溢出,所以几乎所有人都想到用数组,没错,用数组或者字符串都可以,但是如果你在写程序的时候考虑到计算机是如何进行乘法,除法和加减法运算的,我想程序的效率会提高很多.

在两个数相加时,如果你这样判断: 
if (a+b >= 10)
{
     remains = (a+b) % 10;
     array[i] = (a+b) / 10;
}
计算机会进行无数次的乘法和除法,而且做了三次加法运算,自然效率会低. 两个数相加,不会超过20, 
所以可以这样做吧:

int result = a+b ;
remains = result >= 10 ? 1 : 0 ;
array[i] = remains == 0 ? result : result - 10 ;



#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

string first;
string second;
string result;

void AddIt()
{
    int index = 0;
    int tmpResult = 0;
    int remains = 0;

    string::reverse_iterator f_itor = first.rbegin();
    string::reverse_iterator s_itor = second.rbegin();

    result.resize(max(first.length(),second.length()),' ');

    while( f_itor!=first.rend() && s_itor!=second.rend())    
    { 
        tmpResult = *f_itor -'0' + *s_itor - '0' + remains;
        remains = tmpResult >=10 ? 1 : 0;
        result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
        ++f_itor;
        ++s_itor;
        ++index;
    }

    if (first.length() != second.length())
    {
        if (f_itor == first.rend())
        {
            while(s_itor!=second.rend())
            {
                tmpResult = *s_itor - '0' + remains ;
                remains= tmpResult >=10 ? 1 : 0 ;
                result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
                ++s_itor;
                ++index;
            }
        }
        else
        {
            while(f_itor!=first.rend())
            {
                tmpResult = *f_itor - '0' + remains ;
                remains= tmpResult >=10 ? 1 : 0 ;
                result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
                ++f_itor;
                ++index;
            }
        }
        if (remains != 0)
            result.resize(result.length()+1,remains + '0');
    }
    reverse(result.begin(),result.end());
};

int main()
{
    int testcases = 0;

    cin >> testcases;

    for(int i=0;i<testcases;i++)
    {
        cin >> first >> second;
        AddIt();
        cout << result.data() <<endl;
        result = "";
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值