Task : Write a method that takes an integer and converts it to roman numerals where :
- 1 = I
- 4 = IV
- 5 = V
- 9 = IX
- 10 = X
- 40 = XL
- 50 = L
- 90 = XC
- 100 = C
- 400 = CD
- 500 = D
- 900 = CM
- 1000 = M
So, as with all these interview questions, there is a trick to this one and it is in the way that numerals are laid out. It implicitly contains the rules for converting to roman numerals.
Here’s a simple solution.
While the number you’re converting is greater the current highest order of magnitude, keep subtracting the largest number in the list, and writing the equivalent numeral to the output string.
Here is a simple implementation using a dictionary as a lookup. It is very important that you subtract from highest to lowest – you can well imagine why!
public static string NumberToRoman(int number) { Dictionary<int, string> lookup = new Dictionary<int, string>() { {1,"I"}, {4,"IV"}, {5,"V"}, {9,"IX"}, {10,"X"}, {40,"XL"}, {50,"L"}, {90,"XC"}, {100,"C"}, {400,"CD"}, {500,"D"}, {900,"CM"}, {1000,"M"} }; StringBuilder sb = new StringBuilder(); foreach (int key in lookup.Keys.Reverse()) { while(number >= key) { number = number - key; sb.Append(lookup[key]); } } return sb.ToString(); }