Premiumlab  

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

 

   

posted on 2017-06-06 21:18  Premiumlab  阅读(97)  评论(0编辑  收藏  举报