chore(CSharp): added single number determination (#488)
parent
7ce554e085
commit
9d673a8cd1
|
@ -1,6 +1,9 @@
|
|||
# C#
|
||||
For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/)
|
||||
|
||||
## Arrays
|
||||
1. [Single Number](src/Arrays/single-number.cs)
|
||||
|
||||
## Sorts
|
||||
|
||||
1. [Bubble Sort](src/Sorts/bubble-sort.cs)
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Algorithms.Arrays
|
||||
{
|
||||
public class SingleNumber
|
||||
{
|
||||
public static int DetermineSingleNumber(List<int> numbers)
|
||||
{
|
||||
int single = numbers[0];
|
||||
for(int i = 1; i < numbers.Count; i++)
|
||||
{
|
||||
single ^= numbers[i];
|
||||
}
|
||||
|
||||
return single;
|
||||
}
|
||||
|
||||
public static void Main()
|
||||
{
|
||||
List<int> numbers = new List<int> { 7, 1, 2, 3, 1, 7, 2 };
|
||||
Console.WriteLine(DetermineSingleNumber(numbers));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Given a non-empty list of integers, every element except one appears twice
|
||||
* Find out the single one
|
||||
* Time complexity: O(n)
|
||||
* Space complexity: O(1)
|
||||
*/
|
|
@ -0,0 +1,35 @@
|
|||
using NUnit.Framework;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Algorithms.Tests.Arrays
|
||||
{
|
||||
[TestFixture]
|
||||
class SingleNumber
|
||||
{
|
||||
static object[] TestCasesForSingleNumber =
|
||||
{
|
||||
new object[]
|
||||
{
|
||||
new List<int> { 7, 2, 2, 1, 3, 7, 3},
|
||||
1
|
||||
},
|
||||
new object[]
|
||||
{
|
||||
new List<int> { 118 },
|
||||
118
|
||||
},
|
||||
new object[]
|
||||
{
|
||||
new List<int> { 11, 12, 13, 14, 13, 12, 11},
|
||||
14
|
||||
}
|
||||
};
|
||||
|
||||
[TestCaseSource(nameof(TestCasesForSingleNumber))]
|
||||
public void TestSingleNumber_ShouldGetExpectedResult(List<int> numbers, int expected)
|
||||
{
|
||||
int result = Algorithms.Arrays.SingleNumber.DetermineSingleNumber(numbers);
|
||||
Assert.AreEqual(expected, result);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue