Straightforward Ruby Solution, Single Loop, 175 ms


  • 0
    R
    # @param {String} s
    # @return {Integer}
    def roman_to_int(s)
        roman_conversions = {
            "I" => 1,
            "V" => 5,
            "X" => 10,
            "L" => 50,
            "C" => 100,
            "D" => 500,
            "M" => 1000
        }
        
        converted_array = []
        previous = roman_conversions[s[0]]
        
        s.each_char do |char|
            current = roman_conversions[char]
            if current > previous
                converted_array[-1] = (previous - current).abs
            else
                converted_array.push current
            end
            previous = current
        end
        
        converted_array.reduce(:+)
        
    end
    

Log in to reply
 

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