大数加法C++实现

题目:假设输入是2个数字,可能超过long long类型能表示的范围,请输出两数相加的运算结果。

思路:2个数输入的时候,肯定都是用string存的,先将短的数在末尾补0,使得二者一样长。然后挨个位相加,并设置一个标志位专门用来存溢出(即进位)情况。
代码如下:

#include <stdio.h>
#include <string>

using namespace std;

static void compasent0(std::string& inputStr1, std::string& inputStr2)
{
    if (inputStr1.size() < inputStr2.size())
    {
        int diff = inputStr2.size() - inputStr1.size();
        string prefix(diff, '0');
        inputStr1 = prefix + inputStr1;
    }
    else
    {
    {
        int diff = inputStr1.size() - inputStr2.size();
        string prefix(diff, '0');
        inputStr2 = prefix + inputStr2;
    }
    }
}

static bool checkStrValid(const std::string inputStr)
{
    for(const char& ch : inputStr)
    {
        if ((ch < '0') || (ch > '9'))
        {
            return false;
        }
    }
    return true;
}

static std::string BigNumAdd(std::string inputStr1, std::string inputStr2)
{
    if (!checkStrValid(inputStr1) || !checkStrValid(inputStr2))
    {
        printf("ERROR, invalid input!\n");
        return "ERROR";
    }

    compasent0(inputStr1, inputStr2);
    printf("line[%u], inputStr1[%s], inputStr2[%s]\n", __LINE__, inputStr1.c_str(), inputStr2.c_str());

    std::string out(inputStr1.size(), '0');
    int tempSum = 0;
    int overflow = 0;
    for (int i = inputStr1.size() - 1; i > -1; --i)
    {
         tempSum = (int)(inputStr1[i] - '0') + (int)(inputStr2[i] - '0') + overflow;
         if (tempSum < 10)
         {
            out[i] = (char)(tempSum + '0');
            overflow = 0;
         }
         else
         {
            out[i] = (char)(tempSum % 10 + '0');
            overflow = 1;
         }
    }
    if (overflow)
    {
        out = to_string(overflow) + out;
    }

    return out;
}

int main()
{
    std::string inputStr1 = "1906";
    std::string inputStr2 = "456";
    std::string outputStr = BigNumAdd(inputStr1, inputStr2);
    printf("outputStr[%s]\n", outputStr.c_str());

    inputStr1 = "99999999999999999999";
    inputStr2 = "1";
    outputStr = BigNumAdd(inputStr1, inputStr2);
    printf("outputStr[%s]\n", outputStr.c_str());

    return 0;
}

输出是:

./a.out
line[45], inputStr1[1906], inputStr2[0456]
outputStr[2362]
line[45], inputStr1[99999999999999999999], inputStr2[00000000000000000001]
outputStr[100000000000000000000]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码到程攻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值