zoukankan      html  css  js  c++  java
  • 13. Roman to Integer

    https://leetcode.com/problems/roman-to-integer/#/description

    Given a roman numeral, convert it to an integer.

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

    Hint:

    Ⅰ= 1
    Ⅱ = 1+1
    Ⅲ = 2 + 1
    Ⅳ = -1 + 5
    Ⅴ = 5
    Ⅵ = 5 + 1
    Ⅶ = 5 + 2
    Ⅷ = 5+ 3
    Ⅸ = -1 + 10
    Ⅹ = 10
    Ⅺ = 10 + 1
    Ⅻ = 10 + 2


    1 If the previous digit is less than the following one, subtract the previous one. 

    If the previous digit is larger than the following one, add the previous one.

    2 Always add the last digit. 

    Sol:

    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
            z = 0
            for i in range(0, len(s) - 1):
                if roman[s[i]] < roman[s[i+1]]:
                    z -= roman[s[i]]
                else:
                    z += roman[s[i]]
            return z + roman[s[-1]]

    Note:

    1 for i in range(0, len(s) - 1):

        s[i] .... s[i+1]

    We  traverse and compare every adjacent element in s in this way. No index error. 

    s[0] vs. s[1]

    s[1] vs. s[2]

          .  .  .

    s[len(s) - 2] vs. s[len(s) - 1]    =    the one before last one  vs. the last one

    P.S. It's okay to omit 0 in range(o, len(s) - 1 ).

    ex. 

    s = [22,33,44]
    print len(s)
    print s[len(s) - 1]

    ==> 3

           44

       

  • 相关阅读:
    JS定时循环
    JS分组
    中位数 题解
    NOIP2017 D2T3 题解
    CF949E Binary Cards 题解
    友善的树形DP
    300英雄的危机(heroes)
    [北京省选集训2019]图的难题 题解
    洛谷 P1268 树的重量 题解
    洛谷 P2633 Count on a tree 题解
  • 原文地址:https://www.cnblogs.com/prmlab/p/6953710.html
Copyright © 2011-2022 走看看