zoukankan      html  css  js  c++  java
  • [leetcode]Roman to Integer @ Python

    原题地址:https://oj.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.

    解题思路:将罗马数字转换成对应的整数。首先将罗马数字翻转,从小的开始累加,如果遇到CM(M-C=1000-100=900)这种该怎么办呢?因为翻转过来是MC,M=1000先被累加,所以使用一个last变量,把M记录下来,如果下一个数小于M,那么减两次C,然后将C累加上,这个实现比较巧妙简洁。

    代码:

    class Solution:
        # @return an integer
        def romanToInt(self, s):
            numerals = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
            sum=0
            s=s[::-1]
            last=None
            for x in s:
                if last and numerals[x]<last:
                    sum-=2*numerals[x]
                sum+=numerals[x]
                last=numerals[x]
            return sum
  • 相关阅读:
    spring
    ajax
    jquary
    Java web 部分
    长跑马拉松
    面试的标准
    数据预处理——剔除异常值,平滑,归一化
    概率分布
    养生
    平滑的作用
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3779688.html
Copyright © 2011-2022 走看看