
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Questions & Answers
- Program to convert integer to roman numeral in Python
- Roman to Integer in Python
- Integer to Roman in C
- JavaScript program to convert positive integers to roman numbers
- C program to convert roman numbers to decimal numbers
- Convert Tuple to integer in Python
- C# Program to Convert Integer to String
- Java Program to convert boolean to integer
- Java Program to convert integer to boolean
- Java Program to convert integer to octal
- Java Program to convert integer to hexadecimal
- How to convert float to integer in Python?
- Program to convert set of Integer to Array of Integer in Java
- C# program to convert binary string to Integer
- Java Program to convert from integer to String