[LeetCode] 415. Add Strings 字符串相加

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 415. Add Strings 字符串相加相关的知识,希望对你有一定的参考价值。

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

Note:

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

两个只含有数字的字符串相加。

解法: 对于每个字符转成对应的整数,然后相加,结果在写入res。

Python:

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        result = []
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        
        while i >= 0 or j >= 0 or carry:
            if i >= 0:
                carry += ord(num1[i]) - ord(‘0‘);
                i -= 1
            if j >= 0:
                carry += ord(num2[j]) - ord(‘0‘);
                j -= 1
            result.append(str(carry % 10))
            carry /= 10
        result.reverse()

        return "".join(result)

C++:

class Solution {
public:
    string addStrings(string num1, string num2) {
        string res = "";
        int m = num1.size(), n = num2.size(), i = m - 1, j = n - 1, carry = 0;
        while (i >= 0 || j >= 0) {
            int a = i >= 0 ? num1[i--] - ‘0‘ : 0;
            int b = j >= 0 ? num2[j--] - ‘0‘ : 0;
            int sum = a + b + carry;
            res.insert(res.begin(), sum % 10 + ‘0‘);
            carry = sum / 10;
        }
        return carry ? "1" + res : res;
    }
};

    

 

以上是关于[LeetCode] 415. Add Strings 字符串相加的主要内容,如果未能解决你的问题,请参考以下文章

36. leetcode 415. Add Strings

leetcode 415. Add Strings

LeetCode 415. Add Strings

leetcode练习:258. Add Digits & 415. Add Strings

[leetcode-415-Add Strings]

LeetCode 415. Add Strings