2. Add Two Numbers
Description
...
Solution
function addTwoNumbers(
l1: ListNode | null | undefined,
l2: ListNode | null | undefined
) {
let result = new ListNode();
let current = result;
let carry = 0;
let sum: number;
while (l1 || l2) {
sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
current.next = new ListNode(sum % 10);
current = current.next;
carry = sum > 9 ? 1 : 0;
l1 = l1?.next;
l2 = l2?.next;
}
if (carry) {
current.next = new ListNode(carry);
}
return result.next;
}
https://leetcode.com/problems/add-two-numbers/[https://leetcode.com/problems/add-two-numbers/]
Top comments (0)