13. Roman to Integer Leetcode Python
2015-01-30 09:28
387 查看
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这题的做法和前面一体interger to roman 类似 建一个dictionary 去查询。
1.先把string 反转
2. 用一个last去保存上一次的digit
3.如果上次的digit 大于现在的digit 就将值减去两倍的digit 否则 相加。
例如iv 反转过来是VI 直接加之后等于6 实际值为4 需要减去两倍的1
代码如下class Solution:
# @return an integer
def romanToInt(self, s):
dict={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
last=None
sum=0
s=s[::-1]
for elem in s:
if last and dict[last]>dict[elem]:
sum-=2*dict[elem]
sum+=dict[elem]
last=elem
return sum
引用 http://www.cnblogs.com/zuoyuan/p/3779688.html
Input is guaranteed to be within the range from 1 to 3999.
这题的做法和前面一体interger to roman 类似 建一个dictionary 去查询。
1.先把string 反转
2. 用一个last去保存上一次的digit
3.如果上次的digit 大于现在的digit 就将值减去两倍的digit 否则 相加。
例如iv 反转过来是VI 直接加之后等于6 实际值为4 需要减去两倍的1
代码如下class Solution:
# @return an integer
def romanToInt(self, s):
dict={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
last=None
sum=0
s=s[::-1]
for elem in s:
if last and dict[last]>dict[elem]:
sum-=2*dict[elem]
sum+=dict[elem]
last=elem
return sum
引用 http://www.cnblogs.com/zuoyuan/p/3779688.html
相关文章推荐
- Leetcode 13. Roman to Integer The Solution of Python
- [leetcode]Roman to Integer @ Python
- LeetCode 12 Integer to Roman(C,C++,Java,Python)
- leetcode 13. Roman to Integer
- Leetcode 13. Roman to Integer
- [leetcode] 【字符串】13. Roman to Integer
- 【LeetCode with Python】 Roman to Integer
- Leetcode 12. Integer to Roman(python)
- (Java)LeetCode-13. Roman to Integer
- 【一天一道LeetCode】#13. Roman to Integer
- leetcode(10),Roman to Integer(python)
- leetcode Integer to Roman python
- LeetCode 13. Roman to Integer
- LeetCode 13 Roman to Integer (C,C++,Java,Python)
- 13.[LeetCode]Roman to Integer
- 【LeetCode with Python】 Integer to Roman
- 12. Integer to Roman Leetcode Python
- [LeetCode]题解(python):013-Roman to Integer
- [leetcode]Integer to Roman @ Python
- leetcode 13. Roman to Integer