I\'m trying to write a function that converts numbers to roman numerals. This is my code so far; however, it only works with numbers that are less than 400. Is there a quick
Far too late, probably you already solved this, however this is an algorithm which can do the trick for you as well.
Before you start, you could simply do the analysis on Roman literals. For the known ASCII set, only values between 0 and 4000 are supported. If you like to go beyond, you could define your own roman literal then.
Before we start, we know that with the given range above, we can form a roman string from seven occurrences of Roman Literals (I,V,X,L,C,D and M).
Therefore we start with a simple look-up table, based on indices which are calculated in another function. Unknown indices are returned as a white-space character. As I wrote above, one might add additional characters when needed:
///
/// Helper method that looks up a given index to it's roman value.
///
///
/// The roman literal corresponding to it's index
private char DecimalToRoman(int index)
{
switch (index)
{
case 1: return 'I';
case 2: return 'V';
case 3: return 'X';
case 4: return 'L';
case 5: return 'C';
case 6: return 'D';
case 7: return 'M';
default: return ' ';
}
}
The real conversion will happen here:
private string ConvertToRoman(string input)
{
int index = 0;
string output = "";
for (int i = 0; i < input.Length; i++)
{
//Some magic here, this formula will calculate the correct starting
//index of the roman literal to find in the look-up table.
//Since units, tens and hundreds (up to thousand) can be formed of
//three roman literals, we need three indices for looking up the
//correct roman literal.
index = 2 * (input.Length - (i + 1)) + 1;
char digit1 = DecimalToRoman(index);
char digit2 = DecimalToRoman(index + 1);
char digit3 = DecimalToRoman(index + 2);
int originalValue = System.Convert.ToInt32(input[i] - '0');
switch (originalValue)
{
case 1:
case 2:
case 3: for (int j = 0; j < originalValue; j++)
output += digit1.ToString();
break;
case 4: output += digit1.ToString() + digit2.ToString();
break;
case 5: output += digit2.ToString();
break;
case 6:
case 7:
case 8: output += digit2.ToString();
for (int j = 0; j < originalValue - 5; j++)
output += digit1.ToString();
break;
case 9: output += digit1.ToString() + digit3.ToString();
break;
}
}
return output;
}
That is it. If you look for more OO Designed approaches, please accept the answers above this post. There are just a lot of ways to solve this approach.
EDIT: Note that this solution does not cheat (just looking up all occurences of roman literals) as well :)