Skip to content

Commit a95eca5

Browse files
committed
Add solution #2
1 parent e24fa9b commit a95eca5

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
|#|Title|Difficulty|
88
|:---|:---|:---|
99
1|[Two Sum](./0001-two-sum.js)|Easy|
10+
2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium|
1011
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
1112
7|[Reverse Integer](./0007-reverse-integer.js)|Easy|
1213
27|[Remove Element](./0027-remove-element.js)|Easy|

solutions/0002-add-two-numbers.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 2. Add Two Numbers
3+
* https://leetcode.com/problems/add-two-numbers/
4+
* Difficulty: Medium
5+
*
6+
* You are given two non-empty linked lists representing two non-negative integers.
7+
* The digits are stored in reverse order, and each of their nodes contains a single
8+
* digit. Add the two numbers and return the sum as a linked list.
9+
*
10+
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11+
*/
12+
13+
/**
14+
* Definition for singly-linked list.
15+
* function ListNode(val, next) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.next = (next===undefined ? null : next)
18+
* }
19+
*/
20+
/**
21+
* @param {ListNode} l1
22+
* @param {ListNode} l2
23+
* @return {ListNode}
24+
*/
25+
var addTwoNumbers = function(l1, l2) {
26+
const result = new ListNode();
27+
let tail = result;
28+
let carry = 0;
29+
30+
while (l1 || l2 || carry) {
31+
const v1 = l1 ? l1.val : 0;
32+
const v2 = l2 ? l2.val : 0;
33+
const v = v1 + v2 + carry;
34+
35+
tail.next = new ListNode(v % 10);
36+
tail = tail.next;
37+
carry = v >= 10 ? 1 : 0;
38+
l1 = l1 && l1.next;
39+
l2 = l2 && l2.next;
40+
}
41+
42+
return result.next;
43+
};

0 commit comments

Comments
 (0)