lc415. Add Strings

  1. Add Strings Easy

414python

144git

Favorite數組

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

Note:app

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.ui

思路:字符串轉換爲數組,遍歷,經過unicode獲取值,carry用來記錄進位,arr記錄每位的運算結果,最後arr用join鏈接起來spa

代碼:python3code

class Solution(object):
    def addStrings(self, num1, num2):
        l1,l2=list(num1),list(num2)
        carry=0
        arr=[]
        while l1 or l2:
            a=ord(l1.pop())-ord('0') if len(l1)>0 else 0
            b=ord(l2.pop())-ord('0') if len(l2)>0 else 0
            c=a+b+carry
            arr.append(str(c%10))
            carry=int(c/10)
        if carry>0:
            arr.append(str(carry))
        return ''.join(arr)[::-1]
複製代碼
相關文章
相關標籤/搜索