-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-two-numbers.cs
91 lines (80 loc) · 2.28 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// https://leetcode.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
*
*/
using System;
public class Program
{
public static void Main(string[] args)
{
Solution sol = new Solution();
ListNode l1 = new ListNode(7,
new ListNode(8,
new ListNode(7)));
ListNode l3 = new ListNode(9);
ListNode l2 = new ListNode(1,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9,
new ListNode(9))))
))))));
// 787 + 913 = 1700
ListNode sum = sol.AddTwoNumbers(l3,l2);
while(sum!=null){
Console.Write(sum.val);
sum=sum.next;
}
}
}
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 solution = new ListNode(0);
ListNode solutionIndex = null;
int carry = 0;
int s = 0;
while(l1 != null | l2 != null | carry>0){
if(solutionIndex == null) solutionIndex = solution;
else{
solutionIndex.next = new ListNode(0);
solutionIndex = solutionIndex.next;
}
if(l1==null && l2==null){
s = carry;
}
else if(l1 == null ){
s = l2.val + carry;
l2 = l2.next;
}
else if(l2 == null){
s = l1.val + carry;
l1 = l1.next;
}
else{
s = l1.val + l2.val + carry;
l1 = l1.next;
l2 = l2.next;
}
if(s>9){
carry = 1;
s = s - 10;
}
else carry = 0;
solutionIndex.val = s;
}
return solution;
}
}