v9.1.1
Menu

Roman to Integer

easyPROMath & DesignMicrosoft DSA

Convert a Roman numeral string to an integer.

I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Subtractive: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900.

Example

Input
III
Output
3
Reasoning
  • Input: s is a Roman numeral written as a string of symbols, here III: three copies of the symbol I, each worth 11.
  • Math: a numeral's value is the total of its symbols' values, except inside the six subtractive pairs from the description (IV, IX, XL, XC, CD, CM), where the pair as a whole stands for the difference, e.g. IV =5−1=4= 5 - 1 = 4.
  • III contains no V, X or any larger symbol, so none of those pairs can occur and every symbol simply adds: 1+1+1=31 + 1 + 1 = 3.
  • Output: the plain integer 3, not a string.
  • Notice that changing the last symbol to V gives IIV, which is not valid; the valid way to write 44 is IV, where the I now counts as −1-1 instead of +1+1.

Constraints

  • 1 <= len(s) <= 15
  • s is a valid Roman numeral in [1, 3999]

More from Microsoft DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.