Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3aad8d8

Browse files
committed
002 (3) update concise solution
1 parentd076889 commit3aad8d8

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 asa linked list.
11+
*l1 single digit. Add the two numbers and return it asl1 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
publicListNodeaddTwoNumbers(ListNodel1,ListNodel2) {
31-
intcarry =0;
32-
ListNodeh1 =l1;
33-
ListNodeh2 =l2;
3431
ListNodedummy =newListNode(0);
3532
ListNodenode =dummy;
36-
while (h1 !=null ||h2 !=null ||carry >0) {
37-
intn1 =0;
38-
intn2 =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-
intnum =n1 +n2 +carry;
48-
node.next =newListNode(num %10);
33+
intcarry =0;
34+
while (l1 !=null ||l2 !=null ||carry !=0) {
35+
intn1 =l1 !=null ?l1.val :0;
36+
intn2 =l2 !=null ?l2.val :0;
37+
intsum =n1 +n2 +carry;
38+
node.next =newListNode(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
returndummy.next;
5345
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp