diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 3c818b97..1c96ae38 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -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) diff --git a/algorithms/CSharp/src/Arrays/single-number.cs b/algorithms/CSharp/src/Arrays/single-number.cs new file mode 100644 index 00000000..99683512 --- /dev/null +++ b/algorithms/CSharp/src/Arrays/single-number.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace Algorithms.Arrays +{ + public class SingleNumber + { + public static int DetermineSingleNumber(List numbers) + { + int single = numbers[0]; + for(int i = 1; i < numbers.Count; i++) + { + single ^= numbers[i]; + } + + return single; + } + + public static void Main() + { + List numbers = new List { 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) + */ \ No newline at end of file diff --git a/algorithms/CSharp/test/Arrays/single-number.cs b/algorithms/CSharp/test/Arrays/single-number.cs new file mode 100644 index 00000000..88ceea66 --- /dev/null +++ b/algorithms/CSharp/test/Arrays/single-number.cs @@ -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 { 7, 2, 2, 1, 3, 7, 3}, + 1 + }, + new object[] + { + new List { 118 }, + 118 + }, + new object[] + { + new List { 11, 12, 13, 14, 13, 12, 11}, + 14 + } + }; + + [TestCaseSource(nameof(TestCasesForSingleNumber))] + public void TestSingleNumber_ShouldGetExpectedResult(List numbers, int expected) + { + int result = Algorithms.Arrays.SingleNumber.DetermineSingleNumber(numbers); + Assert.AreEqual(expected, result); + } + } +}