20 · String Parsing & Expression Evaluation

#12 Integer to Roman

Mediumsolve on LeetCode ↗

frequently reported atAdobeTCSWalmartMicrosoftAmazonBloomberg

the problem

In plain words

Write an integer num from 1 to 3999 as a standard Roman numeral. The letters are M = 1000, D = 500, C = 100, L = 50, X = 10, V = 5 and I = 1, written from the biggest value to the smallest. Only I, X, C and M may repeat, at most three times in a row. The values 4, 9, 40, 90, 400 and 900 use the subtractive pairs IV, IX, XL, XC, CD and CM.

in num = 3749

out "MMMDCCXLIX"

3000 + 700 + 40 + 9 = MMM + DCC + XL + IX.

in num = 58

out "LVIII"

50 + 5 + 3.

in num = 1994

out "MCMXCIV"

1000 + 900 + 90 + 4 = M + CM + XC + IV.

  • 1 ≤ num ≤ 3999

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #13
      Roman to Integer
      Easyin Parsing
    2. #322
      Coin Change
      Mediumin Dynamic Programming
    3. #66
      Plus One
      Easyin Math & Numbers