[LeetCode]Add Strings

题目描述:

LeetCode 415. Add Strings

IMPORTANT:
Solutions which uses a BigInteger library or converting the input strings to another type (such as integer) will result in disqualification of all submissions to this problem.
After the contest ends, users can view accepted submissions code and report cheating solutions.


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.

题目大意:

给定两个以字符串表示的非负整数num1, num2,返回num1与num2的和。

注意:

  1. num1和num2的长度< 5100
  2. num1和num2只包含数字0-9
  3. num1和num2不包含前导0

你不能使用内置的BigInteger库,也不能直接把输入转换为整数。

解题思路:

模拟大数加法,注意进位即可。

Python代码:

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        result = []
        carry = 0
        idx1, idx2 = len(num1), len(num2)
        while idx1 or idx2 or carry:
            digit = carry
            if idx1:
                idx1 -= 1
                digit += int(num1[idx1])
            if idx2:
                idx2 -= 1
                digit += int(num2[idx2])
            carry = digit > 9
            result.append(str(digit % 10))
        return ''.join(result[::-1])

 

本文链接:http://bookshadow.com/weblog/2016/10/09/leetcode-add-strings/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码