Strings Parsing and conversion
137. Roman to Integer
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"
1499Explanation: M is 1000, CD is 400, XC is 90 and IX is 9. Together they make 1499.
Example 2
Input: s = "LXXVIII"
78Explanation: No symbol comes before a larger one, so every symbol adds: 50 + 10 + 10 + 5 + 1 + 1 + 1.
Example 3
Input: s = "MMMCMXCIX"
3999Explanation: 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.
Constraints
1 ≤ s.length ≤ 15sholds only the symbolsI,V,X,L,C,DandM.sis 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.