13. Roman to Integer [easy] (Python)
来源:互联网 发布:水利工程造价软件 编辑:程序博客网 时间:2024/05/06 08:52
题目链接
https://leetcode.com/problems/roman-to-integer/
题目原文
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目翻译
给定一个罗马数字,将其转成整数。输入限制在1到3999之间。
思路方法
做题的第一步要理解题。说实话,我是不清楚罗马数字的记法的,所以查了一下资料,这里也简单介绍一下吧。
罗马数字采用七个罗马字母作数字:
I(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。
记数的方法:
1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 III=3;
2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 VIII=8、XIII=12;
3. 小的数字(限于 I、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 IV=4、IX=9;
4. 在一个数的上面画一条横线,表示这个数增值 1,000 倍。
常用数字记法举例:
思路一
根据上面说的计数方法的前三条。对于输入的罗马数字字符串,从后向前扫描,遇到前面数大于等于后面的最大数的时候,相加;遇到前面数小于后面的最大数的时候,相减。
代码
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ digits = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} sum = 0 maxDigit = 1 for i in xrange(len(s)-1, -1, -1): if digits[s[i]] >= maxDigit: maxDigit = digits[s[i]] sum += digits[s[i]] else: sum -= digits[s[i]] return sum
思路二
仅考虑相邻的罗马数字的大小情况。对于输入的罗马数字字符串,从后向前扫描,遇到前面数大于等于后面数的时候,相加;遇到前面数小于后面数的时候,相减。(该思路也可以从前向后扫描)
代码
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ digits = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} sum = digits[s[len(s)-1]] for i in xrange(len(s)-1, 0, -1): cur = digits[s[i]] pre = digits[s[i-1]] sum += pre if pre >= cur else -pre return sum
说明
上面两个思路都可以AC,但其实隐含了一些条件,比如有些罗马数字的写法是不合法的。所以考虑这个问题的时候,想的太多反而比较难做AC。
比如,XVILCDM,如果按照第一个思路结果是500-100-50-1-5-10=334;但如果按照第二个思路,则结果是500-100-50-1+(5+10) = 364。
所以我觉得,题目描述不够清晰,如果对罗马数字的表示规则不熟悉,这个题目还是不要太纠结了。。。
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51448537
- 13. Roman to Integer [easy] (Python)
- LeetCode 13. Roman to Integer -- Easy
- Easy-题目13:13. Roman to Integer
- Leetcode 13. Roman to Integer (Easy) (cpp)
- Leetcode: 13. Roman to Integer(Week2, Easy)
- 13. Roman to Integer python
- Leetcode[Easy] -- Roman to Integer
- [LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
- LeetCode 13 Roman to Integer (easy)——python
- Roman to Integer(python)
- 13. Roman to Integer Leetcode Python
- [leetcode:python]13.Roman to Integer
- [Leetcode 13, Easy] Roman To Integer
- 【LeetCode】(13)Roman to Integer(Easy)
- Easy 13题 Roman to Integer
- LeetCode #13 - Roman to Integer - Easy
- Easy 4 Roman to Integer(13)
- Leetcode OJ 13 Roman to Integer [Easy]
- 正则表达式语法
- access文件操作函数应用实例
- 【软件】IDEA web项目里包含node_modules 一直处于make状态
- 小sugar呀——筛法求素数
- Intellij IDEA 创建Web项目并在Tomcat中部署运行
- 13. Roman to Integer [easy] (Python)
- linux常用的命令
- 四则运算
- 高精度-hdu_1047_Integer Inquiry
- SQL和NoSQL数据库的技术差别
- IOS多线程开发其实很简单
- vmware workstation11安装mac10.9系统
- Android的核心服务是指那些
- 钱咖赚钱软件使用心得