Here's a simple algorithm to convert a number into its Roman numeral representation:
main.cs
publicstaticstringConvertToRoman(int number){
if (number < 1 || number > 3999)
thrownew ArgumentOutOfRangeException("number", "Argument must be between 1 and 3999");
StringBuilder result = new StringBuilder();
while (number >= 1000)
{
result.Append("M");
number -= 1000;
}
if (number >= 900)
{
result.Append("CM");
number -= 900;
}
if (number >= 500)
{
result.Append("D");
number -= 500;
}
if (number >= 400)
{
result.Append("CD");
number -= 400;
}
while (number >= 100)
{
result.Append("C");
number -= 100;
}
if (number >= 90)
{
result.Append("XC");
number -= 90;
}
if (number >= 50)
{
result.Append("L");
number -= 50;
}
if (number >= 40)
{
result.Append("XL");
number -= 40;
}
while (number >= 10)
{
result.Append("X");
number -= 10;
}
if (number >= 9)
{
result.Append("IX");
number -= 9;
}
if (number >= 5)
{
result.Append("V");
number -= 5;
}
if (number >= 4)
{
result.Append("IV");
number -= 4;
}
while (number >= 1)
{
result.Append("I");
number -= 1;
}
return result.ToString();
}
1392 chars
88 lines
Usage example:
main.cs
int number = 1234;
string roman = ConvertToRoman(number);
Console.WriteLine("{0} = {1}", number, roman);
// Output: 1234 = MCCXXXIV