Leetcode 13. Roman to Integer The Solution of Python
来源:互联网 发布:淘宝网店推广要钱吗? 编辑:程序博客网 时间:2024/06/04 19:20
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Python:
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ dic={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1} res,pre=0,0 for index,n in enumerate(s[::-1]): if dic[n]>=pre: res+=dic[n] else: res-=dic[n] pre=dic[n] return res
和上一题一样,比较简单,这里还有别人的一种思路。
Python 2:
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ dic = { 'I': lambda i: -1 if s[i + 1] in ['V', 'X'] else 1, 'X': lambda i: -10 if s[i + 1] in ['L', 'C'] else 10, 'C': lambda i: -100 if s[i + 1] in ['D', 'M'] else 100, 'V': lambda i: 5, 'L': lambda i: 50, 'D': lambda i: 500, 'M': lambda i: 1000, } x = 0 s += '@' for i, ch in enumerate(s[:-1]): x += dic[ch](i) return x
附上罗马数字的换算方法:
(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个;
(2)不能把基本数字 V 、L 、D中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个;
(3)V 和 X 左边的小数字只能用 Ⅰ;
(4)L 和 C 左边的小数字只能用 X;
(5)D 和 M 左边的小数字只能用 C。
0 0
- Leetcode 13. Roman to Integer The Solution of Python
- Leetcode 12. Integer to Roman The Solution of Python
- Leetcode 8. String to Integer (atoi) The Solution of Python
- LeetCode #12 Integer to Roman C# Solution
- 13. Roman to Integer Leetcode Python
- [leetcode:python]13.Roman to Integer
- 【Leetcode】【python】Integer to Roman
- 【Leetcode】【python】Roman to Integer
- Leetcode-Roman to Integer-Python
- LeetCode 13. Roman to Integer
- [LeetCode]13.Roman to Integer
- LeetCode --- 13. Roman to Integer
- [Leetcode] 13. Roman to Integer
- [leetcode] 13.Roman to Integer
- leetcode 13. Roman to Integer
- leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- [LeetCode]13. Roman to Integer
- sql考试二
- day2作业
- java中的基础《1》
- Linux上的free命令详解
- AOJ 848 分数拆分
- Leetcode 13. Roman to Integer The Solution of Python
- 【mvc】——jquery.fom.js的核心方法ajaxsubmit实例
- java多线程模式:Future模式
- IMweb小白学习Day2
- 毕业论文用尾注添加参考文献
- eclipse build path的选项说明
- C#遍历DataSet中数据的几种方法总结
- App性能优化之内存优化
- DOM删除操作: