-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution.java
70 lines (53 loc) · 1.79 KB
/
Solution.java
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
60
61
62
63
64
65
66
67
68
69
70
/*
@lc id : 2 Add Two Numbers
@author : rohit
@date : 01/07/2020
@url : https://leetcode.com/problems/add-two-numbers/
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//Create a dummy node for resukt
ListNode resHead = new ListNode(0);
ListNode curr = resHead;
int carry = 0, currSum;
while(l1 != null && l2 != null){
currSum = carry + l1.val + l2.val;
if(currSum > 9)
carry = 1;
else carry = 0;
curr.next = new ListNode(currSum % 10);
curr = curr.next;
l1 = l1.next;
l2 = l2.next;
}
//If both lists have been traversed and carry is left to be
//added to result
if(l1 == null && l2 == null && carry == 1)
curr.next = new ListNode(1);
//This will run when l1 has more elements than l2
while(l1 != null){
currSum = carry + l1.val;
if(currSum > 9)
carry = 1;
else carry = 0;
curr.next = new ListNode(currSum % 10);
l1 = l1.next;
curr = curr.next;
}
if(carry == 1)
curr.next = new ListNode(1);
//This will run when l2 has more elements than l1
while(l2 != null){
currSum = carry + l2.val;
if(currSum > 9)
carry = 1;
else carry = 0;
curr.next = new ListNode(currSum % 10);
l2 = l2.next;
curr = curr.next;
}
if(carry == 1)
curr.next = new ListNode(1);
return resHead.next;
}
}