guarantee了输入,简单好多 = =
ruby code实现如下
# @param {String} s
# @return {Integer}
def roman_to_int(s)
symbols = {"I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000}
result = 0
length = s.length
pos = 0
while(pos < length-1 ) do
if symbols[s[pos]] >= symbols[s[pos+1]]
result += symbols[s[pos]]
pos += 1
else
result += (symbols[s[pos+1]] - symbols[s[pos]])
pos += 2
end
end
if pos == length-1
result += symbols[s[pos]]
end
result
end
runtime 208ms
应该有更好的方法吧=,=