2_Add Two Numbers

2. 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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution 1: detailed version

add from first element till the last. Remember to have a carry variable. If sum is larger than 10, then carry is 1. Otherwise carry is 0.

# 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
        """
        ret = ListNode(-1)
        cur = ret
        carry = 0
        while l1 or l2:
            if l1:
                value1 = l1.val
                l1 = l1.next
            else:
                value1 = 0
            if l2:
                value2 = l2.val
                l2 = l2.next
            else:
                value2 = 0
            if value1 + value2 + carry >= 10:
                cur_sum = value1 + value2 + carry - 10
                carry = 1
            else:
                cur_sum = value1 + value2 + carry
                carry = 0
            cur.next = ListNode(cur_sum)
            cur = cur.next
        if carry == 1:
            cur.next = ListNode(1)
        return ret.next

Solution 2: compressed version

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ret = ListNode(-1)
        cur = ret
        carry = 0
        while l1 or l2 or carry == 1:
            cur_sum, carry = carry, 0
            if l1:
                cur_sum += l1.val
                l1 = l1.next
            if l2:
                cur_sum += l2.val
                l2 = l2.next
            if cur_sum > 9:
                cur_sum -= 10
                carry = 1
            cur.next = ListNode(cur_sum)
            cur = cur.next
        return ret.next

Last updated