From 4b1394c5507ac354b8312fabf725ef1e4b3fcb9d Mon Sep 17 00:00:00 2001 From: Dmytro Bogatov <dmytro@dbogatov.org> Date: Sun, 16 Aug 2020 17:05:17 -0400 Subject: [PATCH] Add Lonely Integer. --- src/hacker-rank/LonelyInteger.cs | 28 ++++++++++++++++++++++++++++ test/hacker-rank/LonelyInteger.cs | 14 ++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/hacker-rank/LonelyInteger.cs create mode 100644 test/hacker-rank/LonelyInteger.cs diff --git a/src/hacker-rank/LonelyInteger.cs b/src/hacker-rank/LonelyInteger.cs new file mode 100644 index 0000000..821727f --- /dev/null +++ b/src/hacker-rank/LonelyInteger.cs @@ -0,0 +1,28 @@ +namespace CodingInterview.HackerRank +{ + /// <summary> + /// You will be given an array of integers. + /// All of the integers except one occur twice. + /// That one is unique in the array. + /// + /// Given an array of integers, find and print the unique element. + /// + /// For example, a = [1, 2, 3, 4, 3, 2, 1], the unique element is 4. + /// </summary> + public class LonelyInteger + { + /// <summary> + /// Finds the unique element + /// </summary> + /// <param name="a">An array of integers where each integer occurs twice except one, which occurs once</param> + /// <returns>The integer which occurs once</returns> + public long Solve(int[] a) + { + for (var i = 1; i < a.Length; i++) + { + a[0] = a[0] ^ a[i]; + } + return a[0]; + } + } +} diff --git a/test/hacker-rank/LonelyInteger.cs b/test/hacker-rank/LonelyInteger.cs new file mode 100644 index 0000000..e134458 --- /dev/null +++ b/test/hacker-rank/LonelyInteger.cs @@ -0,0 +1,14 @@ +using Xunit; + +namespace CodingInterview.Tests.HackerRank +{ + public class LonelyInteger + { + [Fact] + public void TestCases() + { + // From Hacker Rank + Assert.Equal(4, new CodingInterview.HackerRank.LonelyInteger().Solve(new int[] { 1, 2, 3, 4, 3, 2, 1 })); + } + } +} -- GitLab