题解 | #大数加法#

大数加法

https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算两个数之和
# @param s string字符串 表示第一个整数
# @param t string字符串 表示第二个整数
# @return string字符串
#
class Solution:
    def solve(self, s: str, t: str) -> str:
        # write code here
        s_list = list(s)
        t_list = list(t)
        next = 0
        res = []
        while len(s_list) > 0 and len(t_list) > 0:
            pop_num = int(s_list.pop()) + int(t_list.pop()) + next
            if pop_num >= 10:
                next = 1
            else:
                next = 0
            pop_num = str(pop_num)
            res.append(pop_num[len(pop_num) - 1])

        if len(s_list) == 0 and len(t_list) == 0:
            if next == 1:
                res.append("1")
            res.reverse()
            return "".join(res)

        if len(t_list) == 0:
            while len(s_list) > 0:
                add_num = next + int(s_list.pop())
                if add_num >= 10:
                    next = 1
                else:
                    next = 0
                add_num = str(add_num)
                res.append(add_num[len(add_num) - 1])

        if len(s_list) == 0:
            while len(t_list) > 0:
                add_num = next + int(t_list.pop())
                if add_num >= 10:
                    next = 1
                else:
                    next = 0
                add_num = str(add_num)
                res.append(add_num[len(add_num) - 1])
        if next == 1:
            res.append("1")
        res.reverse()
        return "".join(res)

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务