Roman to integer conversion

Question:

Hi I’m trying to do a Roman to integer leetcode problem, I did everything I assigned a value to everything and with a map function and I get the exact letter, the input is like this

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

the problem is I get the letters as a string like [‘L’][‘V’][‘I’][‘I’][‘I’]
How can I make the "L" as a string to be The variable that is assigned a value of 50

I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
s = "LVIII"
length = len(s)
numbers = list(map(list, s))
x = 0
while x < length:
    print(numbers[x])
    x = x + 1
Asked By: Isaac

||

Answers:

make dictionary mapping

dict_ = {'I':1,
         'V':5,
         'X':10,
         'L':50,
         'C':100,
         'D':500,
         'M':1000}

s = list("LVIII")
sum = 0
for x in s :
    sum+= dict_[x]
#op
58
Answered By: qaiser

Based on answer of qaiser I recommend to additionally check if there is, e.g., a ‘I’ before a ‘V’. In this case the ‘I’ must be subtracted from ‘V’, i.e., 5-1=4.

dict_ = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

s = list("LVIII")    
res = 0
i = 0
while i < len(s):        
    if s[i] == 'I' and i < len(s)-1:
        if s[i+1] != 'I':
            res += dict_[s[i+1]] - dict_[s[i]]
            i += 2    
            continue
    res += dict_[s[i]]
    i += 1
print(res)

# output = 58

and with input
s = list("LIV")

# output = 54

I’m sure there is a more concise/pythonic way, but for the first attempt…

Answered By: luk_dsp
class Solution:
def romanToInt(self, s: str) -> int:
    mapping = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    }
    result = 0
    for i in range(len(s)):
        result += mapping[s[i]]
        if i > 0 and mapping[s[i]] > mapping[s[i - 1]]:
            result -= 2 * mapping[s[i - 1]]

    return result
Answered By: Abhijit Sarkar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.