Leetcode 13 Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

如果左边字母的值小于右边,则减去左边的,防止溢出,最后一个值一定需要加上去

def roman_to_int(s)
    h = {"I" => 1,"V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000}
    sum = 0
    (s.length-1).times do |i|
      if h[s[i]]< h[s[i+1]]
        sum -= h[s[i]]
      else
        sum += h[s[i]]
      end
    end
    sum += h[s[-1]]
end

 

posted @ 2015-07-05 19:54  lilixu  阅读(107)  评论(0编辑  收藏  举报