From 9d673a8cd10b9c957e658a92e2f0f0d5a92df2ee Mon Sep 17 00:00:00 2001 From: Waqar Hassan Khan Date: Mon, 27 Sep 2021 00:04:55 +0600 Subject: [PATCH] chore(CSharp): added single number determination (#488) --- algorithms/CSharp/README.md | 3 ++ algorithms/CSharp/src/Arrays/single-number.cs | 33 +++++++++++++++++ .../CSharp/test/Arrays/single-number.cs | 35 +++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 algorithms/CSharp/src/Arrays/single-number.cs create mode 100644 algorithms/CSharp/test/Arrays/single-number.cs 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); + } + } +}