forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0002-add-two-numbers.java
55 lines (53 loc) · 1.5 KB
/
0002-add-two-numbers.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
/*
Name - Add Two Numbers
Link - https://leetcode.com/problems/add-two-numbers/
Time Complexity - O(m + n)
Space Complexity - o(1)
Note - make use of modulo (get remainder) and division (get quotient)
*/
class Solution {
public ListNode addTwoNumbers(ListNode first, ListNode second) {
int q = 0;
int r = 0;
int sum = 0;
ListNode head = null;
ListNode temp = null;
while (first != null || second != null) {
sum =
q +
(
((first != null) ? first.val : 0) +
((second != null) ? second.val : 0)
);
r = sum % 10;
q = sum / 10;
ListNode newNode = new ListNode(r);
if (head == null) {
head = newNode;
} else {
temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = null;
}
if (first != null) {
first = first.next;
}
if (second != null) {
second = second.next;
}
}
if (q > 0) {
ListNode newNode = new ListNode(q);
temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = null;
}
return head;
}
}