Simple Ruby Solution


  • 0
    C
    NUMERALS = {
            "M" => 1000,
            "D" => 500,
            "C" => 100,
            "L" => 50,
            "X" => 10,
            "V" => 5,
            "I" => 1,
            :none => 0
            }
    
    def roman_to_int(s)
        result = 0
        s.chars.each_with_index do |char, idx|
            nxt = idx >= s.length - 1 ? :none : s[idx + 1]
            NUMERALS[char] < NUMERALS[nxt] ? result -= NUMERALS[char] : result += NUMERALS[char]
        end
        result
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.