Skip to content

Instantly share code, notes, and snippets.

@statox
Created June 21, 2021 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statox/48dc2cc1fddf5e3f674a723ba0154df0 to your computer and use it in GitHub Desktop.
Save statox/48dc2cc1fddf5e3f674a723ba0154df0 to your computer and use it in GitHub Desktop.
Leetcode: Add two numbers
// https://leetcode.com/submissions/detail/508355858/
/**
* 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}
*/
var addTwoNumbers = function (l1, l2) {
let result;
let prev;
let carry = 0;
while (l1 || l2) {
const a = l1 ? l1.val : 0;
const b = l2 ? l2.val : 0;
l1 = l1 ? l1.next : null;
l2 = l2 ? l2.next : null;
let s = a + b + carry;
if (s > 9) {
s = s - 10;
carry = 1;
} else {
carry = 0;
}
if (!prev) {
prev = new ListNode(s);
result = prev;
} else {
const node = new ListNode(s);
prev.next = node;
prev = node;
}
}
if (carry !== 0) {
const node = new ListNode(carry);
prev.next = node;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment