Add Two Numbers

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.

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

https://leetcode.com/problems/add-two-numbers/solution/

注意三种情况:

  1. 两个list长度不一样 l1 = [1,2,3] l2=[2,3]

  2. 其中一个为null。l1 = [1,2,3] l2=[ ]

  3. 处理到最后,链尾加一个额外的值,如果carry最后等于一

# 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
        """
        dummy = l = ListNode(0)
        carry = 0
        while l1 and l2:
            sumV = carry + l1.val + l2.val
            l.next = ListNode(sumV%10)
            carry = sumV/10
            l = l.next
            l1 = l1.next
            l2 = l2.next
        while l1:
            sumV = carry+ l1.val
            l.next = ListNode(sumV%10)
            carry = sumV/10
            l = l.next
            l1 = l1.next
        while l2:
            sumV = carry+ l2.val
            l.next = ListNode(sumV%10)
            carry = sumV/10
            l = l.next
            l2 = l2.next
        if carry != 0:
            l.next = ListNode(carry)
        return dummy.next

简化

# 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
        """
        dummy = l = ListNode(0)
        carry = 0
        while l1 or l2:
            sum = carry
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            carry = sum/10
            sum = sum%10
            l.next = ListNode(sum)
            l = l.next
        if carry != 0:
            l.next = ListNode(carry)
        return dummy.next

Last updated

Was this helpful?