算法练习 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.