美文网首页
力扣<415>字符串相加(使用zip_longest函数解决)

力扣<415>字符串相加(使用zip_longest函数解决)

作者: 楠木cral | 来源:发表于2020-08-05 12:01 被阅读0次

题目描述:

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
提示:
num1 和num2 的长度都小于 5100
num1 和num2 都只包含数字 0-9
num1 和num2 都不包含任何前导零
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-strings

个人解答:

使用itertools中的zip_longest()函数来同时遍历两个字符串,不过先将两个字符串倒置计算,函数中使用fillvalue参数实现两个不同长度的字符串取值相加,短的不够取值就取0,刚好达到加法要求.
我的代码使用了2个计数变量,flag表示是否进位,进位就为1,count_0用来统计末尾的0的个数(因为倒置后0会自动去掉,需要保存个数).

class Solution:
def addStrings(self, num1: str, num2: str) -> str:
    from itertools import zip_longest
    res = 0
    flag = 0
    count_0 = 0
    for i in zip_longest(num1[-1::-1], num2[-1::-1], fillvalue=0):

        ans = (int(i[0]) + int(i[1])) + flag  #进位的话后一位计算结果加一
        if ans >= 10:
            ans = ans % 10       # 相加结果大于10的话取余数,并进一位
            flag = 1
        else:
            flag = 0
        
        res = res*10 + ans       # 结果累加
        if res == 0:
            count_0 += 1         # 结果为零多少次就统计0的个数
    if res == 0 and count_0 > 0:  # 处理结果为10, 100, 1000这样的特殊结果,
        count_0 -= 1

    return '1' * flag + str(res)[-1::-1]+ '0'*count_0  # '1' * flag 用来处理结果为10, 100, 1000这样的特殊值

相关文章

网友评论

      本文标题:力扣<415>字符串相加(使用zip_longest函数解决)

      本文链接:https://www.haomeiwen.com/subject/tsvnrktx.html