- Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathAddTwoNumbers.cs
More file actions
Latest commit
41 lines (39 loc) · 1.41 KB
/
Copy pathAddTwoNumbers.cs
File metadata and controls
41 lines (39 loc) · 1.41 KB
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
// Source : https://leetcode.com/problems/add-two-numbers/
// Author : codeyu
// Date : 2016-09-19
/**********************************************************************************
*
* You are given two linked lists representing two non-negative numbers.
* 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.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*
**********************************************************************************/
usingAlgorithms.Utils;
namespaceAlgorithms
{
publicclassSolution002
{
publicstaticListNode<int>AddTwoNumbers(ListNode<int>l1,ListNode<int>l2)
{
ListNode<int>head=newListNode<int>(0);
ListNode<int>current=head;
varcarry=0;
while(l1!=null||l2!=null)
{
varx=l1!=null?l1.Val:0;
vary=l2!=null?l2.Val:0;
vardigit=carry+x+y;
carry=digit/10;
current.Next=newListNode<int>(digit%10);
current=current.Next;
if(l1!=null){l1=l1.Next;}
if(l2!=null){l2=l2.Next;}
}
if(carry>0){current.Next=newListNode<int>(carry);}
returnhead.Next;
}
}
}