12. Integer to Roman
Asked at 29Amazon53Microsoft51Bloomberg51Google45Meta42IBM93tcs70X94Verkada76Adobe74Docusign74UiPath74Warnermedia70Swiggy69AMD69Geico66Booking.com65Wix62Walmart Labs60Palo Alto Networks59Agoda48BlackRock47Zoho42Infosys39DoorDash36Oracle35Salesforce28LinkedIn27TikTok26
Problem
Convert an integer from 1 to 3999 to a Roman numeral, using the subtractive forms IV, IX, XL, XC, CD and CM where they apply.
Example: 58 → "LVIII"; 3749 → "MMMDCCXLIX"
Greedy over the 13 symbol values in descending order, including the subtractive pairs (900 CM, 400 CD, 90 XC, …).
Complexity: O(1) (bounded output).
class Solution:
def intToRoman(self, num: int) -> str:
table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
(50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
res = []
for v, sym in table:
k, num = divmod(num, v)
res.append(sym * k)
return "".join(res)
assert Solution().intToRoman(3749) == "MMMDCCXLIX"
assert Solution().intToRoman(58) == "LVIII"
assert Solution().intToRoman(1994) == "MCMXCIV"
class Solution {
public String intToRoman(int num) {
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"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < vals.length; i++)
while (num >= vals[i]) { num -= vals[i]; sb.append(syms[i]); }
return sb.toString();
}
}
func intToRoman(num int) string {
vals := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
syms := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
var sb strings.Builder
for i, v := range vals { // greedy: largest symbol first
for num >= v {
sb.WriteString(syms[i])
num -= v
}
}
return sb.String()
}