【LeetCode】13. Roman to Integer (Python)

Problem

  1. 罗马数字转为整型数字(阿拉伯数字)。

Algorithmic thinking

1、字典存储形式转化;
2、for循环遍历整个罗马数字(str类型),对其进行一些必要的计算,可以把整个数字完全解析转换完成。

Python3 solution

下面提供两种不同但类似的解法:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
13、罗马数字转为整型数字
"""


class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
        res, p = 0, 'I'
        for c in s[::-1]:
            res, p = res - d[c] if d[c] < d[p] else res + d[c], c

        return res


class Solution2:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """

        roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        res, i = 0, 0
        for i in range(len(s)):
            curr, nxt = s[i], s[i + 1:i + 2]
            print(nxt)
            if nxt and roman[curr] < roman[nxt]:
                res -= roman[curr]
            else:
                res += roman[curr]
        return res


if __name__ == '__main__':
    str1 = 'LII'
    ret = Solution2().romanToInt(str1)
    print(ret)

    list1 = [0, 1, 2, 3]
    for index in range(len(list1)):
        current, next_ = list1[index], list1[index+1:index+2]  # list1[index+1:index+2]是列表类型
        print(current, next_)

    s1 = '123'
    for index in range(len(s1)):
        current, next_ = s1[index], s1[index+1:index+2]        # 字符串的索引可以越界,列表不行。
        print(current, next_)
        # print('溢出?', s1[3:4])

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值