1-
2-
31/**
4- * You are given two linked lists representing two non-negative numbers.
5- *
6- * The digits are stored in reverse order and each of their nodes contain a single digit.
7- *
8- * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
9- *
10- * Output: 7 -> 0 -> 8
2+ * You are given two linked lists representing two non-negative numbers.
3+ *
4+ * <p> The digits are stored in reverse order and each of their nodes contain a single digit.
5+ *
6+ * <p> Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
7+ *
8+ * <p> Output: 7 -> 0 -> 8
119 */
12-
1310public class AddTwoNumbers {
14- public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
15- if (l1 == null )
16- return l2 ;
17- if (l2 == null )
18- return l1 ;
19- ListNode head = new ListNode (0 );
20- ListNode cur = head ;
21- int plus = 0 ;
22- while (l1 != null && l2 != null ) {
23- int sum = l1 .val + l2 .val + plus ;
24- plus = sum / 10 ;
25- sum = sum % 10 ;
26- cur .next = new ListNode (sum );
27- cur = cur .next ;
28- l1 = l1 .next ;
29- l2 = l2 .next ;
30- }
31- if (l1 != null ) {
32- if (plus != 0 ) {
33- cur .next = addTwoNumbers (l1 , new ListNode (plus ));
34- } else {
35- cur .next = l1 ;
36- }
37- } else if (l2 != null ) {
38- if (plus != 0 ) {
39- cur .next = addTwoNumbers (l2 , new ListNode (plus ));
40- } else {
41- cur .next = l2 ;
42- }
43- } else if (plus != 0 ) {
44- cur .next = new ListNode (plus );
45- }
11+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
12+ if (l1 == null ) return l2 ;
13+ if (l2 == null ) return l1 ;
14+ ListNode head = new ListNode (0 );
15+ ListNode cur = head ;
16+ int plus = 0 ;
17+ while (l1 != null && l2 != null ) {
18+ int sum = l1 .val + l2 .val + plus ;
19+ plus = sum / 10 ;
20+ sum = sum % 10 ;
21+ cur .next = new ListNode (sum );
22+ cur = cur .next ;
23+ l1 = l1 .next ;
24+ l2 = l2 .next ;
25+ }
26+ if (l1 != null ) {
27+ if (plus != 0 ) {
28+ cur .next = addTwoNumbers (l1 , new ListNode (plus ));
29+ } else {
30+ cur .next = l1 ;
31+ }
32+ } else if (l2 != null ) {
33+ if (plus != 0 ) {
34+ cur .next = addTwoNumbers (l2 , new ListNode (plus ));
35+ } else {
36+ cur .next = l2 ;
37+ }
38+ } else if (plus != 0 ) {
39+ cur .next = new ListNode (plus );
40+ }
4641
47- return head .next ;
48- }
49- }
42+ return head .next ;
43+ }
44+ }
0 commit comments