-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0002. Add Two Numbers.cs
53 lines (46 loc) · 1.13 KB
/
0002. Add Two Numbers.cs
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
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode p = l1;
ListNode q = l2;
ListNode ans = null;
ListNode c = null;
int m = 0;
while (p != null || q != null)
{
int x = p != null ? p.val : 0;
int y = q != null ? q.val : 0;
int sum = (x + y + m) % 10;
m = (x + y + m) / 10;
if (c == null)
{
c = new ListNode(sum);
ans = c;
}
else
{
c.next = new ListNode(sum);
c = c.next;
}
p = p?.next;
q = q?.next;
}
if (m > 0)
{
c.next = new ListNode(m);
}
return ans;
}
}