【python3】leetcode 445. Add Two Numbers II (Medium)

 445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

1 题目要求不reverse ,所以转换成str求和,然后再转回ListNode  time O(n),space O(n)
 

在discussion里看到一个回复说的隐患 :You cannot do this way, because, integer overflow occurs, if linked list is big enough. The main objective of linked list addition is to use for big integers.如果两个链表长一点,转成int就会超出int的范围。我觉得说的很有道理,所以虽然这种解法Accepted但是还不不太可取。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        a = '';b = ''
        while(l1):
            a += str(l1.val)
            l1 = l1.next
        while(l2):
            b += str(l2.val)
            l2 = l2.next
        c = str(int(a) + int(b))
        l3 = ListNode(int(c[0]))
        node = l3
        for i in range(1,len(c)):
            node.next = ListNode(int(c[i]))
            node = node.next
        return l3

2 虽然不能转成int 但还是可以先把val提出到容器中(如str或list)然后按位相加


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        a = [];b = []
        while(l1):
            a.append(l1.val)
            l1 = l1.next
        while(l2):
            b.append(l2.val)
            l2 = l2.next
        tag = 0
        c = []
        maxlen = max(len(a),len(b))
        #对齐补0
        if len(a) < maxlen:
            for i in range(maxlen - len(a)):a.insert(0,0)
        if len(b) < maxlen:
            for i in range(maxlen - len(b)):b.insert(0,0)        
        
        for i in range(0,maxlen):
            sum = a[maxlen-i-1] + b[maxlen-i-1] + tag
            tag = 1 if sum >= 10 else 0
            c.insert(0,str(sum%10))
        if tag == 1:
            c.insert(0,1)
        l3 = ListNode(c[0])
        node = l3
        for i in range(1,len(c)):
            node.next = ListNode(int(c[i]))
            node = node.next
        node.next = None
        return l3
                

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值