Skip to problem
←

Integer to Roman

Medium 0 attempts

Convert num to its standard Roman numeral representation using I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, and M = 1000.

Write values from largest to smallest, using these six subtractive forms: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, and CM = 900. Other subtractive pairs are not allowed: for example, 49 is XLIX, not IL. Use no spaces or lowercase letters.

Function contract

num is an integer from 1 through 3999.

Output: Return the standard uppercase Roman numeral with no spaces, using subtractive forms IV, IX, XL, XC, CD, and CM.

Example 1

Input
num = 3
Output
"III"

Example 2

Input
num = 1994
Output
"MCMXCIV"

Explanation: 1994 = 1000 + 900 + 90 + 4, represented by M + CM + XC + IV.

Constraints
  • 1 <= num <= 3999

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 13 table entries and at most 15 emitted characters for the allowed input range

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript