标签:name bre += while 表示 dict 数字 get 罗马数字
给定一个罗马数字,转为整数(都是我写的,我很开心,如果我不思考这个问题看起来很难,但是当我思考了他就变得不是那么难)
class Solution(object):
data_dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def get_value(self, symbol):
"""-1表示出问题了"""
return self.data_dict.get(symbol, -1)
def romanToInt1(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 2:
return self.get_value(s) if self.get_value(s) != -1 else 0
i = 0
count = 0
while i < len(s):
cur_value = self.get_value(s[i])
next_value = self.get_value(s[i + 1])
if cur_value == -1:
return count
if cur_value >= next_value:
count += cur_value
i += 1
else:
count += next_value - cur_value
i += 2
if i + 1 == len(s):
count += self.get_value(s[i])
break
return count
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
count = 0
while i < len(s):
if i < len(s) - 1:
cur_value = self.get_value(s[i])
next_value = self.get_value(s[i + 1])
if cur_value == -1:
return count
if cur_value >= next_value:
count += cur_value
else:
count -= cur_value
else:
count += self.get_value(s[i])
i += 1
return count
if __name__ == ‘__main__‘:
s1 = Solution()
s = "D"
print(s1.romanToInt(s))
标签:name bre += while 表示 dict 数字 get 罗马数字
原文地址:https://www.cnblogs.com/liuzhanghao/p/14338323.html