罗马数字转化为数字

题目:

罗马数字转化为数字

代码如下:python3实现

1. 用了最傻的方法,一个字一个字的分析,不过其中还是有可圈可点之处的。比如跳出下一层循环的方法。

class Solution:

    def romanToInt(self, s: str) -> int:

        T = False

        dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

        length = len(s)

        num = 0

        for i in range(length):

            if T:

                T = False

                continue

            if s[i] == 'I' and i + 1 < length:

                if s[i+1] == 'V':

                    num += 4

                    T = True

                elif s[i+1] == 'X':

                    num += 9

                    T = True

                else:

                    num += 1 

            elif s[i] == 'X' and i + 1 < length:

                if s[i+1] == 'L':

                    num += 40

                    T = True

                elif s[i+1] == 'C':

                    num += 90

                    T = True

                else:

                    num += 10

            elif s[i] == 'C' and i + 1 < length:

                if s[i+1] == 'D':

                    num += 400

                    T = True

                elif s[i+1] == 'M':

                    num += 900

                    T = True

                else:

                    num += 100

            else:

                num += dic[s[i]

        if num >= 1 and num <= 3999:

            return num

        else:

            return None

 

2. 充分分析题意,大的在左小的在右。只有表示特殊数字时小的在左大的在右。

class Solution:

    def romanToInt(self, s: str) -> int:

        dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

        length = len(s)

        num = 0 

        for i in range(length):

            if i + 1 < length and dic[s[i]] < dic[s[i+1]]:

                num -= dic[s[i]]

            else:

                num += dic[s[i]]

        return num