chore(CSharp): added single number determination (#488)

pull/498/head
Waqar Hassan Khan 2021-09-27 00:04:55 +06:00 committed by GitHub
parent 7ce554e085
commit 9d673a8cd1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 71 additions and 0 deletions

View File

@ -1,6 +1,9 @@
# C# # C#
For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/) For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/)
## Arrays
1. [Single Number](src/Arrays/single-number.cs)
## Sorts ## Sorts
1. [Bubble Sort](src/Sorts/bubble-sort.cs) 1. [Bubble Sort](src/Sorts/bubble-sort.cs)

View File

@ -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)
*/

View File

@ -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);
}
}
}