Integer to Roman Medium 0 attempts
LeetCode ↗

Integer to Roman

Medium StringHash Table LeetCode

Translate an integer into its Roman numeral form. The Roman numeral system is built from seven base symbols โ€” I (1), V (5), X (10), L (50), C (100), D (500), and M (1000) โ€” combined by addition, except for six special cases (4, 9, 40, 90, 400, 900) where a smaller symbol placed before a larger one means subtraction instead (so IV reads as 4 and IX as 9).

Edge cases: Minimum value is 1. Maximum is 3999.

Input Format
Implement intToRoman(num). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

Input
num = 3
Output
"III"

Example 2

Input
num = 1994
Output
"MCMXCIV"
Constraints
  • 1 <= num <= 3999
Test Cases (2)
Case 1
Args: [3] Expected: "III"
Case 2
Args: [1994] Expected: "MCMXCIV"

Approach: Greedy with Value Table

Map all 13 Roman symbols (including the six subtractive forms) to their values in descending order. Greedily subtract the largest possible value and append the corresponding symbol until the number reaches zero.

javascript
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;
}

Time Complexity: O(1) โ€” bounded by the fixed set of symbols (at most ~15 iterations)

Space Complexity: O(1)

Saved in this browser only. Private to you.

JavaScript