leetcode_13. Roman to Integer 罗马数字转化为阿拉伯数字
2016-10-19 14:18
309 查看
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题意:
给定一串罗马数字,转化为阿拉伯数字
代码:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = dict()
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for i in range(len(s)) :
result = result + dic[s[i]]
if i > 0 and dic[s[i]] > dic[s[i-1]] :
result = result - 2*dic[s[i-1]]
return result
笔记:
参考 http://www.ituring.com.cn/article/179820?utm_source=tuicool:
罗马数字转化为十进制数规则:
基本字符: I、V、X、L、C、D、M
相应的阿拉伯数字表示为:
1、5、10、50、100、500、1000
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
(3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
思路如下:
从左边第一个数字开始,依次加,因为有(3)的情况的存在, 加过以后判断,要是存在(3)的情况,就减去前一个(i-1)*2,因为本来应该减去前面这个小的数, 但是上次一循环还加了一次,于是这次就减去2次。
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题意:
给定一串罗马数字,转化为阿拉伯数字
代码:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = dict()
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for i in range(len(s)) :
result = result + dic[s[i]]
if i > 0 and dic[s[i]] > dic[s[i-1]] :
result = result - 2*dic[s[i-1]]
return result
笔记:
参考 http://www.ituring.com.cn/article/179820?utm_source=tuicool:
罗马数字转化为十进制数规则:
基本字符: I、V、X、L、C、D、M
相应的阿拉伯数字表示为:
1、5、10、50、100、500、1000
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
(3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
思路如下:
从左边第一个数字开始,依次加,因为有(3)的情况的存在, 加过以后判断,要是存在(3)的情况,就减去前一个(i-1)*2,因为本来应该减去前面这个小的数, 但是上次一循环还加了一次,于是这次就减去2次。
相关文章推荐
- 13.罗马数字转化为阿拉伯数字1-3999
- Leetcode刷题记——13. Roman to Integer(罗马数字转换阿拉伯数字)
- Leetcode#12. Roman to Integer (阿拉伯数字转化罗马数字)
- 编了一个简单的把阿拉伯数字转化成中文表示的程序,很粗糙,欢迎大家优化!!!
- Roman to Integer 罗马数字转阿拉伯数字@LeetCode
- leetcode:Roman to Integer(罗马数字转化为罗马数字)
- Javascript 阿拉伯数字转化中国大写数字的函数代码
- 将阿拉伯数字转化成大写的人民币数字
- c++阿拉伯数字转化为中文大写
- 一亿以内的阿拉伯数字大小写的转化
- 把阿拉伯数字转化成大写
- LeetCode Roman to Integer 罗马数字转阿拉伯数字
- 汉字数目与阿拉伯数字转化之二
- 将阿拉伯数字转化为中文数字,如12“一十二”
- 将阿拉伯数字转化为人民币的大写
- Python将阿拉伯数字转化为中文大写
- 汉字数目与阿拉伯数字转化之一
- java小程序:阿拉伯数字金额转化为中国文字数字表示的金额
- 将阿拉伯数字转化为中文对应的数字
- leetcode:Integer to Roman(整数转化为罗马数字)