-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0002-Add-two-numbers.cs
More file actions
57 lines (49 loc) · 1.31 KB
/
0002-Add-two-numbers.cs
File metadata and controls
57 lines (49 loc) · 1.31 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0002.Add_two_numbers
{
public class _0002_Add_two_numbers
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
// Linked List
ListNode res = new ListNode();
ListNode curr = res;
int num1 = 0;
int num2 = 0;
int carry = 0;
while ((l1 != null || l2 != null))
{
if (l1 != null)
{
num1 = l1.val;
l1 = l1.next;
}
if (l2 != null)
{
num2 = l2.val;
l2 = l2.next;
}
carry = carry + num1 + num2;
num1 = 0;
num2 = 0;
if (carry > 9)
{
curr.next = new ListNode(carry % 10);
carry /= 10;
}
else
{
curr.next = new ListNode(carry);
carry = 0;
}
curr = curr.next;
}
if (carry != 0)
curr.next = new ListNode(carry);
return res.next;
}
}
}