DEV Community

Convert Roman Numerals to Integers

Tyler Scott Williams on February 10, 2020

This post is part of my "LeetCode for 1x Developers" series, in which I struggle through LeetCode problems. Sometimes I figure it out, other times ...
Collapse
 
habilain profile image
David Griffin • Edited

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)

Collapse
 
ogdenstudios profile image
Tyler Scott Williams

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

Collapse
 
pozil profile image
Philippe Ozil • Edited

Interesting problem, thanks for sharing.

@everyone who might read and for the sake of not re-inventing the wheel, note that there's a CSS rule for list style:

ol { list-style-type: upper-roman; }