Created
December 19, 2018 17:30
-
-
Save khan-hasan/4016adf6454d3f813c2af1ac275e2f32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class RomanDecode | |
{ | |
public static int Solution(string roman) | |
{ | |
// Hashtable representing the numeric value of each roman numeral key | |
Hashtable romanKeys = new Hashtable() { | |
{'I', 1}, | |
{'V', 5}, | |
{'X', 10}, | |
{'L', 50}, | |
{'C', 100}, | |
{'D', 500}, | |
{'M', 1000} | |
}; | |
// If roman is one numeral, return numeric value | |
if (roman.Length == 1) | |
{ | |
return (int)romanKeys[roman.ToCharArray()[0]]; | |
} | |
else | |
{ | |
// Array of chars in roman in reverse order | |
char[] romanChars = roman.ToCharArray(); | |
Array.Reverse(romanChars); | |
// Numeric value of roman | |
int total = 0; | |
// Loop over each numeral in romanChars | |
for (int i = 0; i < romanChars.Length; i++) | |
{ | |
if (i == romanChars.Length - 1) | |
{ | |
total += ((int)romanKeys[romanChars[i]]); | |
} | |
else | |
{ | |
// If the numeral at the following index is less than the current numeral, subtract them, and add result to total | |
if ((int)romanKeys[romanChars[i + 1]] < (int)romanKeys[romanChars[i]]) | |
{ | |
total += ((int)romanKeys[romanChars[i]] - (int)romanKeys[romanChars[i + 1]]); | |
i += 1; | |
} | |
else | |
{ | |
total += ((int)romanKeys[romanChars[i]]); | |
} | |
} | |
} | |
return total; | |
} | |
throw new NotImplementedException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment