Leetcode415. 高精度加法

Leetcode415. Add Strings

题目

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题分析

这道题乍一看第一想法就是将两个数转成十进制数,然后将两个数相加之后再转成字符串,但是这样的话很容易出现当数字很大的时候求和溢出的情况,进而得不到正确的结果。所以我们就只能另辟蹊径了。
我们可以模拟加法竖式计算的过程,用变量carry来记录进位的情况,从最末位开始相加,如果出现进位,就用carry来记录进位的数字,最后只需再判断一下首位相加是否出现进位的情况就可以了,问题就顺利地得到了解决~

源代码

class Solution {
public:
    string addStrings(string num1, string num2) {
        int number1 = 0, number2 = 0, size, size1 = num1.size(), size2 = num2.size(), number, carry = 0;
        string s = "";
        char c;
        if (size1 > size2) {
            for (int i = 0; i < size1 - size2; i++) {
                num2 = '0' + num2;
            }
            size = size1;
        }
        else if (size1 < size2) {
            for (int i = 0; i < size2 - size1; i++) {
                num1 = '0' + num1;
            }
            size = size2;
        }
        for (int i = size - 1; i >= 0; i--) {
            int bit = num1[i] - '0' + num2[i] - '0' + carry;
            if (bit < 10) {
                c = bit + '0';
                carry = 0;
            }
            else {
                c = bit % 10 + '0';
                carry = bit / 10;
            }
            s = c + s;
        }
        if (carry != 0) {
            c = carry + '0';
            s = c + s;
        }
        return s;
    }
};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值