Integer to Roman Explained
Problem Statement
Given an integer num
(between 1 and 3999), convert it to a Roman numeral string. Roman numerals use symbols I (1), V (5), X (10), L (50), C (100), D (500), and M (1000), with subtraction rules for cases like IV (4) and IX (9). This problem tests your ability to map numbers to symbols systematically.
Example
Input: num = 1994
Output: "MCMXCIV"
Explanation: 1000 = M, 900 = CM, 90 = XC, 4 = IV.
Code
Java
Python
JavaScript
public class Solution { public String intToRoman(int num) { int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.length; i++) { while (num >= values[i]) { sb.append(symbols[i]); num -= values[i]; } } return sb.toString(); } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.intToRoman(1994)); // "MCMXCIV" } }
def int_to_roman(num): values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] result = "" for i in range(len(values)): while num >= values[i]: result += symbols[i] num -= values[i] return result # Example usage print(int_to_roman(1994)) # "MCMXCIV"
function intToRoman(num) { const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; let result = ""; for (let i = 0; i < values.length; i++) { while (num >= values[i]) { result += symbols[i]; num -= values[i]; } } return result; } // Example usage console.log(intToRoman(1994)); // "MCMXCIV"
Explanation
- Define arrays for Roman numeral values and their corresponding symbols, including subtraction cases (e.g., CM = 900).
- Iterate through the values from largest to smallest.
- For each value, append its symbol and subtract it from
num
as many times as possible. - Continue until
num
becomes 0. - Return the resulting string.
Note
The time complexity is O(1) since the input is bounded (1 to 3999), and the loop iterations are constant. Ensure the input is within the valid range.