8.罗马数字转整数

题目描述:
  • 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
  • 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
  • 示例
  • 输入: "LVIII" 输出: 58 解释: L = 50, V= 5, III = 3.
python代码:
class Solution:
    def romanToInt(self, s: str) -> int:
        nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        s = list(s)
        res = 0
        index = 0
        while index < 13 and s:
            while s:
                tmpt_char = s[0]
                if len(romans[index]) == 2 and len(s)>=2:
                    tmpt_char += s[1]
                    if tmpt_char == romans[index]:
                        res += nums[index]
                        s.pop(0)
                        s.pop(0)
                    else:
                        break
                else:
                    if tmpt_char == romans[index]:
                        res += nums[index]
                        s.pop(0)
                    else:
                        break
            index += 1
        return res
另一版代码:
  • 思路:(1). 默认都加一遍;(2). 六种特殊情况:当前数大于前一个数。(3). 因为 (1) 时候已经加了一遍,所以后面减掉2倍的前一个数。
class Solution:
    def romanToInt(self, s: str) -> int:
        dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        num = 0
        num += dict[s[0]]
        for i in range(1, len(s)):
            num += dict[s[i]]
            if dict[s[i]] > dict[s[i-1]]:
                num -= 2*dict[s[i-1]]
        return num
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值