Python Solution


  • 3
    X

    Plus all value of char, and subtract double value of char which are smaller than next one.
    所有字符值加起来,如果某个字符比右边的小,减去它的二倍。

        l = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
        result = 0
        for i in range(len(s)):
            result += l[s[i]]
            if i > 0 and l[s[i-1]] < l[s[i]]:
                result -= l[s[i-1]]*2
        return result

  • 0
    B

    Plus all value of char which are greater than next one, and minus all value of char while are less than next one. Of course, the final one to be added.

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


  • 0
    O

    This is my solution:

    class Solution(object):
        def romanToInt(self, s):
            switcher={
                'I':1,
                'V':5,
                'X':10,
                'L':50,
                'C':100,
                'D':500,
                'M':1000,
            }
            sum=0
            q=0
            for i in s[::-1]:
                p=switcher.get(i,"nothing")
                print(p)
                if p>=q:
                    sum+=p
                else:
                    sum-=p
                q=p
            return sum
    

  • 0
    S

    This is elegant but it does not reject illegal input string like "DMXI"


  • 0
    N

    def romanMap():
    map=(("M", 1000),("CM", 900),("D", 500),("CD", 400),("C", 100),("XC", 90),("L", 50),("XL", 40),("X", 10),("IX", 9),("V", 5),("V", 4),("I", 1))
    return map
    firstNum=ns([0])
    secondNum=ns([1])
    def main():
    ns=str(input("Enter a roman numeral"))
    total=0
    result=0
    while ns:
    firstNum=(romanMap(ns[0]))
    secondNum=(romanMap(ns[1])
    if firstNum is len(ns)>1 or secondNum-1:
    total=total+firstNum
    ns=ns[1:]
    else:
    total=total+ns[1]-ns[0]
    ns=ns[2:]
    print (total)
    main()


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.