Skip to content

Commit 2402dc5

Browse files
committed
Add hexadecimal exercise
1 parent 7f0c5be commit 2402dc5

3 files changed

Lines changed: 76 additions & 1 deletion

File tree

config.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
"linked-list",
4646
"wordy",
4747
"tournament",
48-
"acronym"
48+
"acronym",
49+
"hexadecimal"
4950
],
5051
"deprecated": [
5152

hexadecimal/Example.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text.RegularExpressions;
5+
6+
public class Hexadecimal
7+
{
8+
private static readonly Dictionary<char, int> AlphaValues = new Dictionary<char, int>
9+
{
10+
{ 'a', 10 },
11+
{ 'b', 11 },
12+
{ 'c', 12 },
13+
{ 'd', 13 },
14+
{ 'e', 14 },
15+
{ 'f', 15 }
16+
};
17+
18+
public static int ToDecimal(string value)
19+
{
20+
if (IsNotValidHexadecimal(value)) return 0;
21+
22+
return value.Select((c, i) => GetNumericValue(c) * SixteenToThePowerOf(value.Length - i - 1)).Sum();
23+
}
24+
25+
private static bool IsNotValidHexadecimal(string value)
26+
{
27+
return Regex.IsMatch(value, "[^0-9abcdef]", RegexOptions.IgnoreCase);
28+
}
29+
30+
private static int GetNumericValue(char value)
31+
{
32+
if (char.IsNumber(value))
33+
return (int)char.GetNumericValue(value);
34+
return AlphaValues[value];
35+
}
36+
37+
private static int SixteenToThePowerOf(int power)
38+
{
39+
return (int)Math.Pow(16, power);
40+
}
41+
}

hexadecimal/HexadecimalTest.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using NUnit.Framework;
2+
3+
[TestFixture]
4+
public class HexadecimalTest
5+
{
6+
// change Ignore to false to run test case or just remove 'Ignore = true'
7+
[TestCase("1", Result = 1)]
8+
[TestCase("c", Result = 12, Ignore = true)]
9+
[TestCase("10", Result = 16, Ignore = true)]
10+
[TestCase("af", Result = 175, Ignore = true)]
11+
[TestCase("100", Result = 256, Ignore = true)]
12+
[TestCase("19ace", Result = 105166, Ignore = true)]
13+
[TestCase("19ace", Result = 105166, Ignore = true)]
14+
public int Hexadecimal_converts_to_decimal(string hexadecimal)
15+
{
16+
return Hexadecimal.ToDecimal(hexadecimal);
17+
}
18+
19+
[Ignore]
20+
[Test]
21+
public void Invalid_hexadecimal_is_decimal_0()
22+
{
23+
Assert.That(Hexadecimal.ToDecimal("carrot"), Is.EqualTo(0));
24+
}
25+
26+
[TestCase("000000", Result = 0, Ignore = true)]
27+
[TestCase("ffffff", Result = 16777215, Ignore = true)]
28+
[TestCase("ffff00", Result = 16776960, Ignore = true)]
29+
public int Octal_can_convert_formatted_strings(string hexidecimal)
30+
{
31+
return Hexadecimal.ToDecimal(hexidecimal);
32+
}
33+
}

0 commit comments

Comments
 (0)