标签:
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
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4622876.html