Skip to content

Commit 3aad8d8

Browse files
committed
002 (3) update concise solution
1 parent d076889 commit 3aad8d8

File tree

1 file changed

+10
-18
lines changed

1 file changed

+10
-18
lines changed

src/_002_AddTwoNumbers/Solution.java

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*
99
* You are given two linked lists representing two non-negative numbers.
1010
* The digits are stored in reverse order and each of their nodes contain
11-
* a single digit. Add the two numbers and return it as a linked list.
11+
* l1 single digit. Add the two numbers and return it as l1 linked list.
1212
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
1313
* Output: 7 -> 0 -> 8
1414
*
@@ -28,26 +28,18 @@ public class Solution {
2828
* Be careful to test null before reference node's value
2929
*/
3030
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
31-
int carry = 0;
32-
ListNode h1 = l1;
33-
ListNode h2 = l2;
3431
ListNode dummy = new ListNode(0);
3532
ListNode node = dummy;
36-
while (h1 != null || h2 != null || carry > 0) {
37-
int n1 = 0;
38-
int n2 = 0;
39-
if (h1 != null) {
40-
n1 = h1.val;
41-
h1 = h1.next;
42-
}
43-
if (h2 != null) {
44-
n2 = h2.val;
45-
h2 = h2.next;
46-
}
47-
int num = n1 + n2 + carry;
48-
node.next = new ListNode(num % 10);
33+
int carry = 0;
34+
while (l1 != null || l2 != null || carry != 0) {
35+
int n1 = l1 != null ? l1.val : 0;
36+
int n2 = l2 != null ? l2.val : 0;
37+
int sum = n1 + n2 + carry;
38+
node.next = new ListNode(sum % 10);
4939
node = node.next;
50-
carry = num / 10;
40+
carry = sum / 10;
41+
l1 = l1 != null ? l1.next : null;
42+
l2 = l2 != null ? l2.next : null;
5143
}
5244
return dummy.next;
5345
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy