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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
Python
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur = dummy = ListNode(None)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
node = ListNode(carry % 10)
cur.next = node
cur = cur.next
carry /= 10
return dummy.next
JavaScript
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = (l1, l2) => {
const dummy = new ListNode(0);
let cur = dummy;
let carry = 0;
let a = l1;
let b = l2;
while (a || b || carry > 0) {
if (a !== null) {
carry += a.val;
a = a.next;
}
if (b !== null) {
carry += b.val;
b = b.next;
}
cur.next = new ListNode(carry % 10);
carry = Math.trunc(carry / 10);
cur = cur.next;
}
return dummy.next;
};