溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++實(shí)現(xiàn)兩個(gè)超大的字符數(shù)字相加的算法的代碼

發(fā)布時(shí)間:2020-07-12 11:32:17 來源:網(wǎng)絡(luò) 閱讀:698 作者:chinaman_U 欄目:編程語言

如下資料是關(guān)于C++實(shí)現(xiàn)兩個(gè)超大的字符數(shù)字相加的算法的代碼。

#include <iostream>
#include <string>
#include <stack>

using namespace std;
void deleteLeadingZeros(string& num){

    if(num[0] == '0'){
        unsigned int strtCpyIndex = 0;
        strtCpyIndex = num.find_first_not_of("0");
        string temp = num.substr(strtCpyIndex);
        num = temp;
    }
}
void equalizeLength(string& num1 , string& num2, char pad = '0'){

    if(num1.size() < num2.size()){
        unsigned int diff = num2.size() - num1.size();
        string temp;
            temp += pad;
        temp += num1;
        num1 = temp;
    }
    else if(num2.size() < num1.size()){
        unsigned int diff = num1.size() - num2.size();
        string temp;
            temp += pad;
        temp += num2;
        num2 = temp;
    }
}

string addLargeNumbers(string num1, string num2)
{   

    if(num1.empty())
        return num2;
    else if(num2.empty())
        return num1;

    stack<short> addResult; 
    string returnResult = "";   

    deleteLeadingZeros(num1);
    deleteLeadingZeros(num2);

    equalizeLength(num1,num2);

    int lastAddElem = num1.size()- 1;

    bool hasCarry = false;

    for(int i = lastAddElem; i >= 0; --i)
    {

        if(result < 10 && !hasCarry)
            addResult.push(result);
        else
        {           
            if(hasCarry){
                hasCarry = result < 10 ? false : true;
                addResult.push(result%10);
            }
            else
            {
                hasCarry = true;
                addResult.push(result % 10 );
            }
        }

    }
    if(hasCarry)
        addResult.push(result/10);

    while(addResult.size()){
        returnResult += (addResult.top() + '0');        
        addResult.pop();
    }

    return returnResult;
}

int main()
{       
    string num1,num2;
    while(true){
        cout<<"Enter 2 integer for addition : ";
        cin >> num1 >> num2;
        cout <<num1 << "+" << num2 <<" = "<<addLargeNumbers(num1,num2)<<endl;
    }

}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI