Skip to content

Commit 0231d19

Browse files
authored
Update and rename index.js to addTwoNumbers.md
1 parent 5485b41 commit 0231d19

File tree

2 files changed

+53
-28
lines changed

2 files changed

+53
-28
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
Approach : Elementary Math
2+
3+
<img width="569" alt="Screenshot 2022-04-08 at 7 32 33 PM" src="https://user-images.githubusercontent.com/34129569/162451709-5de2bf3e-fa18-4025-946d-6b836cfad897.png">
4+
5+
Algorithm
6+
7+
Just like how you would sum two numbers on a piece of paper,
8+
we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 0 \ldots 90…9, summing two digits may "overflow". For example 5 + 7 = 125+7=12. In this case, we set the current digit to 22 and bring over the carry = 1carry=1 to the next iteration. carrycarry must be either 00 or 11 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 199+9+1=19.
9+
10+
The pseudocode is as following:
11+
12+
* Initialize current node to dummy head of the returning list.
13+
* Initialize carry to 0.
14+
* Initialize p1 and p2 to head of l1 and l2 respectively.
15+
* Loop through lists l1l1 and l2l2 until you reach both ends.
16+
* Set x to node pp's value. If p1 has reached the end of l1, set to 0.
17+
* Set yy to node qq's value. If qq has reached the end of l2, set to 0.
18+
* Set sum = x + y + carry.
19+
* Update carry = sum / 10.
20+
* Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
21+
* Advance both p1 and p2.
22+
* Check if carry = 1, if so append a new node with digit 11 to the returning list.
23+
* Return dummy head's next node.
24+
25+
```js
26+
/**
27+
* Definition for singly-linked list.
28+
* function ListNode(val) {
29+
* this.val = val;
30+
* this.next = null;
31+
* }
32+
*/
33+
/**
34+
* @param {ListNode} l1
35+
* @param {ListNode} l2
36+
* @return {ListNode}
37+
*/
38+
var addTwoNumbers = function(l1, l2) {
39+
const dummy = new ListNode();
40+
let ptr = dummy;
41+
let p1 = l1;
42+
let p2 = l2;
43+
let c = 0;
44+
while (p1 || p2 || c) {
45+
const sum = (p1 ? p1.val : 0) + (p2 ? p2.val : 0) + c;
46+
c = Math.floor(sum / 10);
47+
ptr.next = new ListNode(sum % 10);
48+
ptr = ptr.next;
49+
p1 = p1 ? p1.next : p1;
50+
p2 = p2 ? p2.next : p2;
51+
}
52+
return dummy.next;
53+
};

leetcode/add-two-numbers/index.js

Lines changed: 0 additions & 28 deletions
This file was deleted.

0 commit comments

Comments
 (0)