forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.js
More file actions
Latest commit
59 lines (51 loc) · 1.43 KB
/
Copy pathAddTwoNumbers.js
File metadata and controls
59 lines (51 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* A LinkedList based solution for Add Two Numbers
*
*/
import{Node}from'./SinglyLinkedList.js'
/*
Problem Statement:
Given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
Link for the Problem: https://leetcode.com/problems/add-two-numbers/
*/
classAddTwoNumbers{
constructor(){
this.dummyNode=newNode(0)
}
solution(firstList,secondList){
letfirstRunner=firstList
letsecondRunner=secondList
lettail=this.dummyNode
letcarry=0
while(firstRunner!=null||secondRunner!=null){
constfirstNumber=firstRunner ? firstRunner.data : 0
constsecondNumber=secondRunner ? secondRunner.data : 0
constsum=carry+firstNumber+secondNumber
carry=parseInt(sum/10)
tail.next=newNode(sum%10)
tail=tail.next
if(firstRunner){
firstRunner=firstRunner.next
}
if(secondRunner){
secondRunner=secondRunner.next
}
}
if(carry>0){
tail.next=newNode(carry%10)
}
returnthis.dummyNode.next
}
solutionToArray(){
constlist=[]
letcurrentNode=this.dummyNode.next
while(currentNode){
list.push(currentNode.data)
currentNode=currentNode.next
}
returnlist
}
}
export{AddTwoNumbers}