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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
Result
Runtime: 116 ms, faster than 85.61% of JavaScript online submissions for Add Two Numbers.
Memory Usage: 47.2 MB, less than 71.47% of JavaScript online submissions for Add Two Numbers.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = (l1, l2) => {
let current = new ListNode(0);
const returnList = current;
let sum, carry = 0;
while (l1 || l2 || carry > 0) {
sum = 0;
if (l1 !== null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 !== null) {
sum += l2.val;
l2 = l2.next;
}
sum += carry;
current.next = new ListNode(sum % 10);
current = current.next;
carry = sum > 9 ? 1 : 0;
}
return returnList.next;
};
Result
Runtime: 23 ms, faster than 86.94% of PHP online submissions for Add Two Numbers.
Memory Usage: 19.3 MB, less than 69.59% of PHP online submissions for Add Two Numbers.
class Solution
{
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers(ListNode $l1, ListNode $l2): ?ListNode
{
$plus = bcadd($this->getNumber($l1), $this->getNumber($l2));
$len = strlen($plus);
$node = null;
for ($i = 0; $i < $len; $i++) {
$node = new ListNode($plus[$i], $node);
}
return $node;
}
function getNumber(ListNode $node): string
{
$res = '';
while ($node->next) {
$res .= $node->val;
$node = $node->next;
}
return strrev($res . $node->val);
}
}
Result
Runtime: 69 ms, faster than 94.10% of Python3 online submissions for Add Two Numbers.
Memory Usage: 13.8 MB, less than 86.42% of Python3 online submissions for Add Two Numbers.
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1 + v2 + carry, 10)
n.next = ListNode(val)
n = n.next
return root.next