-
-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy patharray-sum.cs
45 lines (37 loc) · 1.11 KB
/
array-sum.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
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ArraySum(new object[] { 3, 4, new object[] { 5, 6, new object[] { 6, 7 } } })); // 31
Console.WriteLine(ArraySum(new object[] { 3, 4, new object[] { 5, 6 }, new object[] { 6, 7 } })); // 31
}
public static int ArraySum(object input)
{
if (input == null)
return 0;
int index = 0;
int sum = 0;
if (input is Array)
{
object[] inp = (object[])input;
while (index < inp.Length)
{
object currentValue = inp[index++];
if (currentValue is int)
{
sum += (int)currentValue;
}
if (currentValue is Array)
{
sum += ArraySum(currentValue);
}
}
}
return sum;
}
}
}