oneby7

Strings Parsing and conversion

137. Roman to Integer

Easy

You are given a string s that holds a Roman numeral. Return the number it stands for.

Roman numerals use seven symbols: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500 and M is 1000. A numeral is usually written from the largest symbol to the smallest, and its value is the sum of its symbols. So XVI is 10 + 5 + 1 = 16, and MMCC is 2200.

Six pairs are written the other way round, with a smaller symbol in front of a larger one. Such a pair is worth the larger value minus the smaller one: IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900. So XIV is 14, not 16.

Example 1

Input: s = "MCDXCIX"

Output: 1499

Explanation: M is 1000, CD is 400, XC is 90 and IX is 9. Together they make 1499.

Example 2

Input: s = "LXXVIII"

Output: 78

Explanation: No symbol comes before a larger one, so every symbol adds: 50 + 10 + 10 + 5 + 1 + 1 + 1.

Example 3

Input: s = "MMMCMXCIX"

Output: 3999

Explanation: 3000 + 900 + 90 + 9. This is the largest value s can stand for.

Check your understanding

Work out the answer for this input before you write any code.

s = "XLIV"

Constraints

  • 1 ≤ s.length ≤ 15
  • s holds only the symbols I, V, X, L, C, D and M.
  • s is a valid Roman numeral, written the usual way, for a number from 1 to 3999.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.