python实现两个超长度大数相加

#-*- coding: utf-8 -*-

# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
# Example:
#
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: List
        :type l2: List
        :rtype: List
        """
        l1 = list(reversed(l1))
        l2 = list(reversed(l2))
        l1,l2 = self.judgeLen(l1,l2)
        print(l1,l2)
        add_nums = []
        for i in range(len(l1)):
            add_num,flag = self.judgeCarry(l1[i],l2[i])
            if flag==0:
                add_nums.append(add_num)
            else:
                add_nums.append(add_num)
                try:
                    l1[i+1] = l1[i+1]+1
                except:
                    continue
        if add_nums[-1]==0:
            add_nums.append(1)
        print(list(reversed(add_nums)))

    def judgeCarry(self,a,b):
        if a+b>9:
            return [(a+b)%10,1]
        else:
            return [a+b,0]

    def judgeLen(self,l1,l2):
        lenl1 = len(l1)
        lenl2 = len(l2)
        add_len = []
        for i in range(abs(lenl2-lenl1)):
            add_len.append(0)
        if lenl1>=lenl2:
            for i in range(abs(lenl2-lenl1)):
                l2.append(0)
            # print([l1,add_len])
            return [l1,l2]
        else:
            for i in range(abs(lenl2-lenl1)):
                l1.append(0)
            add_len.append(l1)
            # print([l2,add_len])
            return [l2,l1]

if __name__ == '__main__':
    S = Solution()
    S.addTwoNumbers([2,4,3,5,6,4,7,4],[5,6,4,4,5,6,7])

思路:反转list,各个位数相加,进位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值