Leetcode415 字符串相加

Leetcode415 字符串相加_第1张图片
思路:
从末尾开始相加,进位可以最后统一处理,因为再怎么进也是最多只进一位

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        # 确保1里是更长的字符串
        if len(num1) < len(num2):
            num1_list = list(num2)
            num2_list = list(num1)
        else:
            num1_list = list(num1)
            num2_list = list(num2)
        num1_list.reverse()
        num2_list.reverse()
        for pointer in range(0, len(num2_list)):
            num1_list[pointer] = int(num1_list[pointer]) + int(num2_list[pointer])
        last_remain = 0
        print(num1_list)
        for pointer in range(0, len(num1_list)):
            current_num = int(num1_list[pointer]) + last_remain
            if current_num >= 10:
                last_remain = current_num // 10
                num1_list[pointer] = current_num % 10
            else:
                num1_list[pointer] = current_num
                last_remain = 0
        answer = ""
        #print(num1_list,last_remain)
        if last_remain > 0:
            answer = str(last_remain)
        num1_list.reverse()
        for each_num in num1_list:
            answer += str(each_num)
        print(answer)
        return answer

你可能感兴趣的:(Leetcode中等题,python,leetcode)