Skip to content

Instantly share code, notes, and snippets.

@JonCanning
Last active December 20, 2015 11:09
Show Gist options
  • Save JonCanning/6120931 to your computer and use it in GitHub Desktop.
Save JonCanning/6120931 to your computer and use it in GitHub Desktop.
RomanNumeral
struct RomanNumeral
{
static readonly List<RomanNumeral> RomanNumerals;
readonly int integer;
readonly string roman;
static RomanNumeral()
{
RomanNumerals = new List<RomanNumeral>
{
new RomanNumeral(1000, "M"),
new RomanNumeral(900, "CM"),
new RomanNumeral(500, "D"),
new RomanNumeral(400, "CD"),
new RomanNumeral(100, "C"),
new RomanNumeral(90, "XC"),
new RomanNumeral(50, "L"),
new RomanNumeral(40, "XL"),
new RomanNumeral(10, "X"),
new RomanNumeral(9, "IX"),
new RomanNumeral(5, "V"),
new RomanNumeral(4, "IV"),
new RomanNumeral(1, "I")
};
}
RomanNumeral(int integer, string roman)
{
this.integer = integer;
this.roman = roman;
}
public RomanNumeral(int integer) : this(integer, IntegerToRoman(integer)) {}
public RomanNumeral(string roman) : this(RomanToInteger(roman), roman) {}
public static implicit operator int(RomanNumeral romanNumeral)
{
return romanNumeral.integer;
}
public override string ToString()
{
return roman;
}
static int RomanToInteger(string roman)
{
var integer = 0;
foreach (var rn in RomanNumerals)
{
while (roman.Any())
{
if (!roman.StartsWith(rn.roman))
break;
integer += rn.integer;
roman = roman.Substring(rn.roman.Length);
}
}
return integer;
}
static string IntegerToRoman(int i)
{
var stringBuilder = new StringBuilder();
foreach (var rn in RomanNumerals)
{
while (i >= rn.integer)
{
i -= rn.integer;
stringBuilder.Append(rn.roman);
}
}
return stringBuilder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment