算法練習 Leetcode 力扣 415. Add Strings 解法

add binary基本一樣。

關鍵點:
從右邊開始加
把長的input作為第一個,給最左邊加0用來進位(如果需要的話),最後看要不要去掉
python裡面要用ord,chr 來做char/ascii轉換

python解法

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num1 is None or len(num1) == 0:
            return num2
        if num2 is None or len(num2) == 0:
            return num1
        if len(num1) < len(num2):
            return self.addStrings(num2, num1)
        n1 = ['0'] + [c for c in num1]
        n2 = [c for c in num2]
        i = len(n1) - 1
        j = len(n2) - 1
        while i >= 0:
            if j >= 0:
                n1[i] = chr(ord(n1[i]) + ord(n2[j]) - ord('0'))
            if n1[i] > '9':
                n1[i] = chr(ord(n1[i]) - 10)
                n1[i - 1] = chr(ord(n1[i - 1]) + 1)
            i -= 1
            j -= 1
        ans = ''.join(n1)
        if ans[0] == '0':
            return ans[1:]
        return ans

Leave a Comment

Your email address will not be published.