您的位置:首页 > 编程语言 > C语言/C++

Roman to Integer

2016-06-12 16:04 190 查看

c++

class Solution {
public:
int romanToInt(string s) {
if (s.empty()) return 0;
unordered_map<char, int> dict = { { 'I' , 1 },{ 'V' , 5 },
{ 'X' , 10 },{ 'L' , 50 },{ 'C' , 100 },{ 'D' , 500 },{ 'M' , 1000 } };
int cum = dict[s.back()];
for (int i = s.size() - 2; i >= 0; --i) {
if (dict[s[i]] < dict[s[i + 1]])
cum -= dict[s[i]];
else
cum += dict[s[i]];
}
return cum;
}
};


python

class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
if not s: return 0
dict = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
s = list(s)
cum = dict[s[-1]]
for i in xrange(len(s)-2,-1,-1):
if dict[s[i]] < dict[s[i+1]]:
cum -= dict[s[i]]
else:
cum += dict[s[i]]

return cum


reference:

https://leetcode.com/discuss/22867/clean-o-n-c-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言