LeetCode 415. Add Strings(字串相加)python3版本
阿新 • • 發佈:2018-12-11
程式碼轉載自:點選這裡可以檢視 我給加了很詳細的註解,這樣看起來就方便多了,尤其是像我一樣的新手
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ #長度減一是字元在字串中最後的位置 i = len(num1) - 1 j = len(num2) - 1 result = '' #進位 carry = 0 while i >= 0 or j >= 0: if i >= 0: #用acsii編碼來做出計算,用數字的ascii碼減去0對 #應的ascii編碼,最終結果即為這個數字 carry += ord(num1[i]) - ord('0') if j >= 0: carry += ord(num2[j]) - ord('0') #每次將計算的結果而非進位加到字串result中 result += chr(carry % 10 + ord('0')) #求出進位 carry //= 10 i -= 1 j -= 1 if carry == 1: result += '1' return result[::-1]