FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Problem-Solving-Map/linkedList/AddTwoNumbers.java at main · OmarShawky1/Problem-Solving-Map · GitHub
OmarShawky1
/
Problem-Solving-Map
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Problem-Solving-Map
/
linkedList
/
AddTwoNumbers.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
60 lines (46 loc) · 1.63 KB
Breadcrumbs
Problem-Solving-Map
/
linkedList
/
AddTwoNumbers.java
Copy path
File metadata and controls
60 lines (46 loc) · 1.63 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
linkedList
;
public
class
AddTwoNumbers
{
public
ListNode
addTwoNumbers1
(
ListNode
l1
,
ListNode
l2
) {
ListNode
head
=
new
ListNode
(
0
);
// Create a dummy node, return its next
ListNode
currHead
=
head
;
int
carry
=
0
;
// If there is still any number in l1, l2 or carry, continue adding
while
(
l1
!=
null
||
l2
!=
null
||
carry
!=
0
) {
int
sum
=
carry
;
// Use carry
if
(
l1
!=
null
&&
l2
!=
null
)
sum
+=
l1
.
val
+
l2
.
val
;
else
if
(
l1
!=
null
)
sum
+=
l1
.
val
;
else
if
(
l2
!=
null
)
sum
+=
l2
.
val
;
//Erase carry after using it
carry
=
0
;
//Create new carry
if
(
sum
>
9
) {
sum
-=
10
;
carry
=
1
;
}
currHead
.
next
=
new
ListNode
(
sum
);
currHead
=
currHead
.
next
;
if
(
l1
!=
null
)
l1
=
l1
.
next
;
if
(
l2
!=
null
)
l2
=
l2
.
next
;
}
return
head
.
next
;
}
// Same but more compacted
public
ListNode
addTwoNumbers
(
ListNode
l1
,
ListNode
l2
) {
ListNode
dummyHead
=
new
ListNode
(
0
);
ListNode
curr
=
dummyHead
;
int
carry
=
0
;
while
(
l1
!=
null
||
l2
!=
null
||
carry
!=
0
) {
int
l1Val
= (
l1
!=
null
) ?
l1
.
val
:
0
;
int
l2Val
= (
l2
!=
null
) ?
l2
.
val
:
0
;
carry
+=
l1Val
+
l2Val
;
curr
.
next
=
new
ListNode
(
carry
%
10
);
carry
/=
10
;
curr
=
curr
.
next
;
if
(
l1
!=
null
)
l1
=
l1
.
next
;
if
(
l2
!=
null
)
l2
=
l2
.
next
;
}
return
dummyHead
.
next
;
}
public
static
void
test
() {
}
}
Back
|
FazBrowse Home
|
New Git URL