Write a number in Roman numerals
A film credit or a chapter heading wants MCMXCIV rather than 1994.
- The subtractive forms count: 4 is IV, 9 is IX, 40 is XL, 90 is XC, 400 is CD, 900 is CM.
- Only 1 to 3999 can be written; anything outside gives an empty string.
ToRoman(amount: int) → string
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public string ToRoman(int amount) {
}
Worked examples
| Call | Result |
|---|---|
ToRoman(1) | "I" |
ToRoman(4) | "IV" |
ToRoman(14) | "XIV" |
ToRoman(1994) | "MCMXCIV" |
Hint
Keep the values and their symbols in one descending table, including the subtractive pairs. Then it is one greedy pass.
Reference solution in C#
public string ToRoman(int amount) {
if (amount < 1 || amount > 3999) return "";
int[] vals = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
string[] syms = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int n = amount;
var sb = new StringBuilder();
for (int i = 0; i < vals.Length; i++) {
while (n >= vals[i]) { sb.Append(syms[i]); n -= vals[i]; }
}
return sb.ToString();
}