Ruby solution


  • 0
    M

    This solution uses the minimum Roman to Arabic map, the algorithm looks at the neighboring characters and decide if a subtraction or addition should be performed.

    Note that the right-most Roman character should always be an addition so I deliberately left out the last char.

    # @param {String} s
    # @return {Integer}
    CONVERSION = {"I" => 1, "X" => 10,  "V" => 5, "L" => 50, "C" => 100, "D" => 500, "M" => 1000}.freeze
    def roman_to_int(s)
      i, value = 0, 0
      while i < s.size - 1
         cur_val, next_val = CONVERSION[s[i]], CONVERSION[s[i+1]]
         flag = cur_val < next_val ? -1 : 1
         value += cur_val * flag
         i += 1
      end
              
      value += CONVERSION[s[s.size-1]]
      value         
    end
    

Log in to reply
 

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