Instagram
youtube
Facebook
Twitter

Roman to Integer Leetcode Solution

This tutorial will solve the roman to integer problem from leetcode in python.

Task: 

Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9. 
X can be placed before L (50) and C (100) to make 40 and 90. 
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.


Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.


Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].

Solution:

class Solution:
    def romanToInt(self, s: str) -> int:
        d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        
        sum_ = 0
        a = 0
        for c in range(len(s)-1, -1, -1):
            
            if d[s[c]] >= a:
                sum_ += d[s[c]]
                # print(sum_)
            else:
                sum_ -= d[s[c]]
            a = d[s[c]]            
            
        return sum_

Steps:

step1: first we make a dictionary to store the values for the particular roman symbol.

step2: now we declare two variables sum_ to return the integer and a to store the previous roman symbol integer value to compare.

step3: now we loop from right to left to the given string and compare the value of d[s[c]] to variable a, if it is greater then we add it to our sum_ variable otherwise we subtract the value.

step4: after the loop, we return the sum_ variable as our integer.