Last active
April 12, 2022 16:11
-
-
Save wollmich/fb85d529b195a8008e940e488cb739be to your computer and use it in GitHub Desktop.
This file contains 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
/// <summary> | |
/// Roman | |
/// </summary> | |
public struct Roman | |
{ | |
/// <summary> | |
/// Value | |
/// </summary> | |
public int Value; | |
/// <summary> | |
/// Roman | |
/// </summary> | |
/// <param name="value">Regular Numeral</param> | |
public Roman(int value) | |
{ | |
if (value < 0 || value > 3999) throw new ArgumentOutOfRangeException("Value must be between 0 and 3999"); | |
Value = value; | |
} | |
/// <summary> | |
/// Roman | |
/// </summary> | |
/// <param name="s">Roman Numeral</param> | |
public Roman(string s) | |
{ | |
int value = 0; | |
for (int i = 0; i < s.Length; i++) | |
{ | |
if (i + 1 < s.Length && RomanMap[s[i]] < RomanMap[s[i + 1]]) | |
{ | |
value -= RomanMap[s[i]]; | |
} | |
else | |
{ | |
value += RomanMap[s[i]]; | |
} | |
} | |
if (value < 0 || value > 3999) throw new ArgumentOutOfRangeException("Value must be between 0 and 3999"); | |
Value = value; | |
} | |
/// <summary> | |
/// To String | |
/// </summary> | |
/// <returns>Roman Numeral</returns> | |
public override string ToString() | |
{ | |
int value = Value; | |
StringBuilder s = new StringBuilder(); | |
foreach (var item in NumberMap) | |
{ | |
while (value >= item.Key) | |
{ | |
s.Append(item.Value); | |
value -= item.Key; | |
} | |
} | |
return s.ToString(); | |
} | |
private static readonly Dictionary<char, int> RomanMap = new Dictionary<char, int>() | |
{ | |
{'I', 1}, | |
{'V', 5}, | |
{'X', 10}, | |
{'L', 50}, | |
{'C', 100}, | |
{'D', 500}, | |
{'M', 1000} | |
}; | |
private static readonly Dictionary<int, string> NumberMap = new Dictionary<int, string>() | |
{ | |
{ 1000, "M" }, | |
{ 900, "CM" }, | |
{ 500, "D" }, | |
{ 400, "CD" }, | |
{ 100, "C" }, | |
{ 90, "XC" }, | |
{ 50, "L" }, | |
{ 40, "XL" }, | |
{ 10, "X" }, | |
{ 9, "IX" }, | |
{ 5, "V" }, | |
{ 4, "IV" }, | |
{ 1, "I" }, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment