【lc】415 字符串相加

链接

https://leetcode.cn/problems/add-strings/description/

分析

大数相加而已,倒着遍历,然后相加就好了。

代码

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        num1, num2 = (num1, num2) if len(num1) > len(num2) else (num2, num1)
        r_num1, r_num2 = list(num1)[::-1], list(num2)[::-1]
        res = []
        remains = 0
        for i in range(len(r_num1)):
            if i < len(r_num2):
                tmp_val = int(r_num1[i]) + int(r_num2[i]) + remains
            else:
                tmp_val = int(r_num1[i]) + remains
            res.append(str(tmp_val % 10))
            remains = tmp_val // 10
        if remains > 0:
            res.append(str(remains))
        return ''.join(res[::-1])

 

posted @ 2023-08-25 14:08  BJFU-VTH  阅读(22)  评论(0编辑  收藏  举报