LeetCode算法题解

阅读“关于 5 分钟

Hi! :hand:

LeetCode 第二道题: Add Two Numbers,难度简单。

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 81 Explanation: 342 + 465 = 807.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
11         
12         ListNode ret = null;
13         ListNode l3 = null;
14 
15         var add = 0;
16         while (l1 != null && l2 != null)
17         {
18             var val = l1.val + l2.val + add;
19             add = val / 10;
20             val = val % 10;
21             
22             var node = new ListNode(val);
23             if (l3 == null)
24             {
25                 l3 = node;
26             }
27             else
28             {
29                 l3.next = node;
30                 l3 = node;
31             }
32             
33             if (ret == null)
34             {
35                 ret = node;
36             }
37 
38             l1 = l1.next;
39             l2 = l2.next;
40         }
41 
42         while (l1 != null)
43         {
44             var val = l1.val + add;
45             add = val / 10;
46             val = val % 10;
47             
48             var node = new ListNode(val);
49             if (l3 == null)
50             {
51                 l3 = node;
52             }
53             else
54             {
55                 l3.next = node;
56                 l3 = node;
57             }
58             
59             l1 = l1.next;
60         }
61         
62         while (l2 != null)
63         {
64             var val = l2.val + add;
65             add = val / 10;
66             val = val % 10;
67             
68             var node = new ListNode(val);
69             if (l3 == null)
70             {
71                 l3 = node;
72             }
73             else
74             {
75                 l3.next = node;
76                 l3 = node;
77             }
78 
79             l2 = l2.next;
80         }
81 
82         if (add > 0)
83         {
84             var node = new ListNode(add);
85             if (l3 == null)
86             {
87                 l3 = node;
88             }
89             else
90             {
91                 l3.next = node;
92                 l3 = node;
93             }
94         }
95         
96         return ret;
97     }
98 }

Gist code


To use, see:Jektify - Doc

jektify © 2019  +

Música

Goodbye! :wink:


The word of the day!

Put a very powerful message.