给定一个罗马数字,将其转换为整数。
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
解题:
观察CM = 900, XC = 90 and IV = 4
当前字母 < 后面的字母 , 则减去该数值 ,反之,若是大于后面的值,则加总该数。使用next要注意超出阵列的问题。
RomanValue = { "I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000}def roman_to_int(s) (0..(s.length-1)).sum{ |index| if RomanValue[s[index.next]].nil? RomanValue[s[index]] * 1 else if RomanValue[s[index]] < RomanValue[s[index.next]] RomanValue[s[index]] * -1 else RomanValue[s[index]] * 1 end end }end
如果要写乾净一点,可以使用fetch方法,加入预设值,减少判断
def roman_to_int(s) (0..(s.length-1)).sum{ |index| if RomanValue[s[index]] < RomanValue.fetch(s[index.next],0) RomanValue[s[index]] * -1 else RomanValue[s[index]] * 1 end }end