【LeetCode 简单题】94-字符串相加

声明:

今天是第94道题。给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

  1. num1 和num2 的长度都小于5100.
  2. num1 和num2 都只包含数字 0-9.
  3. num1 和num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

解法1。采取从最低位逐位相加的方式,同时遍历2个字符串,记录进位情况,下面这版代码还是挺简洁的,如下。

执行用时: 68 ms, 在Add Strings的Python3提交中击败了73.73% 的用户

class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        i = len(num1) - 1
        j = len(num2) - 1

        res = ''
        carry = 0
        while i >= 0 or j >= 0:
            if i >= 0:
                carry += int(num1[i])
            if j >= 0:
                carry += int(num2[j])
            res += str(carry%10)
            carry //= 10
            i -= 1    # 注意以下这2步不能少哦
            j -= 1
        if carry == 1:
            res += '1'
        return res[::-1]

解法2。还有种比较傻的方法,也很慢,但可以满足题目要求,就是先各自把str逐位转化为十进制数,在相加后转为str,代码如下。

执行用时: 116 ms, 在Add Strings的Python3提交中击败了15.18% 的用户 

class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        t1 = 0
        for i in num1:
            t1 *= 10
            t1 += ord(i) - ord('0')
        
        t2 = 0
        for i in num2:
            t2 *= 10
            t2 += ord(i) - ord('0')
        
        return str(t1+t2)

结尾

解法1:https://www.polarxiong.com/archives/LeetCode-415-add-strings.html

解法2:LeetCode

备注:

  • eval() 函数用来执行一个字符串表达式,并返回表达式的值。
    • 如:eval(str) = int
    • 如:x=7,eval( '3 * x' )

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/84035961