20 · String Parsing & Expression Evaluation

#13 Roman to Integer

Easysolve on LeetCode ↗

frequently reported atBloombergMicrosoftGoogleTCSAmazonMeta

the problem

In plain words

Roman numerals use seven letters, here from biggest to smallest: M = 1000, D = 500, C = 100, L = 50, X = 10, V = 5 and I = 1. Usually the letters go from big to small and their values add up (VIII = 8). In six cases a smaller letter sits just before a bigger one and is subtracted instead: IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900. Given a valid numeral s, return its value.

in s = "III"

out 3

in s = "LVIII"

out 58

50 + 5 + 3.

in s = "MCMXCIV"

out 1994

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

  • 1 ≤ s.length ≤ 15
  • s uses only I, V, X, L, C, D, M
  • s is a valid numeral for a value from 1 to 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. #12
      Integer to Roman
      Mediumin Parsing
    2. #8
      String to Integer (atoi)
      Mediumin Parsing
    3. #67
      Add Binary
      Easyin Bits