2023年7月8日 星期六

7/8 每日一題(回傳兩組字串相加,禁止使用內置函式以及num1 and num2 直接轉int)

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

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

 

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

 

Constraints:

  • 1 <= num1.length, num2.length <= 104
  • num1 and num2 consist of only digits.
  • num1 and num2 don't have any leading zeros except for the zero itself.




class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        #從個位數開始計算
        res=[] #記錄用
        carry=0  #進位用
        i=len(num1) -1
        j=len(num2) -1
        while i >=0 or j >=0:  
            n1=int(num1[i]) if i >=0 else 0
            n2=int(num2[j]) if j >=0 else 0
            cur_sum=n1+n2+carry #當前位數加總 再加上進位
            carry = cur_sum//10  #大於10進位到下一位
            res.append(str(cur_sum%10)) #%10避免大於10狀況
            i -=1
            j -=1  
        if carry >0 : #如果還有進位
            res.append(str(carry))
        res.reverse() #反轉list
        return ''.join(res)
























標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁