Skip to content
loading...

re: Convert Roman Numerals to Integers VIEW POST

FULL DISCUSSION
 

Special casing all those checks is asking for problems though, and I'm pretty sure it's not that neat. If we assume that the input is a valid Roman numeral (which this code does do; "IIX" is not a valid Roman numeral, but your code will parse it as 10), then the rule is that "if a numeral is smaller than the next numeral, subtract its value". Using that rule gives a much neater function:

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

def roman_to_int(input_string: str) -> int:
    ints = [vals[x] for x in input_string] + [0]
    output = 0
    for current, next in zip(ints, ints[1:]):
        output += -current if current < next else current
    return output

(Apologies for using Python, but I don't trust my JS enough to write it error free) (Edited to add the vals dict so the code actually runs)

 

Ah yeah! Good catch. I think that's a given in the LC problem but I forgot to say it. If it isn't, none of the LC cases provide invalid numerals, haha

code of conduct - report abuse