您的位置:首页 > 其它

(LeetCode) Roman to Integer --- 罗马数字转整数

2016-10-12 10:04 507 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Subscribe to see which companies asked this question
解题分析:
首先要了解,罗马数字对应的整数:

"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000


然后要了解罗马数字的排序方式,从左到右依次从大到小。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def romanToInt(self, s):
digits = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 }
len_s = len(s)
num = 0
for i in range(0, len_s - 1):
cur = digits[s[i]]
next = digits[s[i + 1]]
if cur >= next:
num += cur
else:
num -= cur
num += digits[s[len_s - 1]]
return num

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: