ITPub博客

首页 > IT职业 > IT图书 > C++实现两个超大的字符数字相加的算法的代码

C++实现两个超大的字符数字相加的算法的代码

IT图书 作者:sinlong 时间:2021-09-09 10:18:10 0 删除 编辑


如下资料是关于C++实现两个超大的字符数字相加的算法的代码。

#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;

    }

}

©著作权归作者所有:来自51CTO博客作者chinaman_U的原创作品,如需转载,请注明出处,否则将追究法律责任


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3156/viewspace-2819698/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    0
  • 访问量
    685