【ruby】leetcode 练习 :Roman to Integer

给定一个罗马数字,将其转换为整数。

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

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章