Program to convert roman numeral to integer in Python?



Suppose we have a roman numeral; we have to convert it into number. As we know a Roman numeral is represented by symbols from left to right from greatest to least, the only exception being when representing one less than a symbol. Some roman numeral symbol meanings are as follows:

  • 'M': 1000

  • 'D': 500

  • 'C': 100

  • 'L': 50

  • 'X': 10

  • 'V': 5

  • 'I': 1

So, if the input is like numeral = "MCLXVI", then the output will be 1166, as M = 1000, C = 100, total is 1100, then L = 50, X = 10, VI = 6 so total is 1166.

To solve this, we will follow these steps:

take numeral list as mentioned above

  • ans := 0

  • n := size of numeral

  • for each index idx and value c numeral, do

    • if idx < n - 1 and d[c] < d[numeral[idx + 1]], then

      • ans := ans - d[c]

    • otherwise,

      • ans := ans + d[c]

  • return ans

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, numeral):
      d = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}
      ans = 0
      n = len(numeral)
      for (idx, c) in enumerate(numeral):
         if idx < n - 1 and d[c] < d[numeral[idx + 1]]:
            ans -= d[c]
         else:
            ans += d[c]
      return ans

ob = Solution()
numeral = "MCLXVI"
print(ob.solve(numeral))

Input

"MCLXVI"

Output

1166

Advertisements