1. 程式人生 > >LeetCode羅馬數字轉整數 python解法

LeetCode羅馬數字轉整數 python解法

題目:

羅馬數字包含以下七種字元:I, V, X, LCD 和 M

字元          數值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

例如, 羅馬數字 2 寫做 II ,即為兩個並列的 1。12 寫做 XII ,即為 X + II 。 27 寫做  XXVII, 即為 XX + V + II 。

通常情況下,羅馬數字中小的數字在大的數字的右邊。但也存在特例,例如 4 不寫做 IIII,而是 IV

。數字 1 在數字 5 的左邊,所表示的數等於大數 5 減小數 1 得到的數值 4 。同樣地,數字 9 表示為 IX。這個特殊的規則只適用於以下六種情況:

  • I 可以放在 V (5) 和 X (10) 的左邊,來表示 4 和 9。
  • X 可以放在 L (50) 和 C (100) 的左邊,來表示 40 和 90。 
  • C 可以放在 D (500) 和 M (1000) 的左邊,來表示 400 和 900。

給定一個羅馬數字,將其轉換成整數。輸入確保在 1 到 3999 的範圍內。

Python2種解法:

解法1:

    def romanToInt(self,s):
        i=0
        result=0
        length=len(s)
        while(i<length):
            if s[i]=='I':
                if( i+1<=length-1  and s[i+1]=='V'):
                    result=result+4
                    i=i+2
                elif(i+1<=length-1  and s[i+1]=='X'):
                    result=result+9
                    i=i+2
                else:
                    result=result+1
                    i=i+1

            elif s[i]=='X':
                if(i+1<=length-1  and  s[i+1]=='L'):
                    result=result+40
                    i=i+2
                elif(i+1<=length-1  and s[i+1]=='C'):
                    result=result+90
                    i=i+2
                else:
                    result=result+10
                    i=i+1

            elif s[i]=='C':
                if(i+1<=length-1  and  s[i+1]=='D'):
                    result=result+400
                    i=i+2
                elif(i+1<=length-1  and s[i+1]=='M'):
                    result=result+900
                    i=i+2
                else:
                    result=result+100
                    i=i+1

            elif s[i]=='V':
                result=result+5
                i=i+1

            elif s[i]=='L': 
                result=result+50
                i=i+1

            elif s[i]=='D':
                result=result+500
                i=i+1

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

        return result

解法2:

    def romanToInt1(self, s):
        result=0
        curr=0
        pre=0
        for i in range(len(s)):
            if s[i]== 'I':
                curr=1
            elif s[i]== 'V':
                curr=5
            elif s[i]== 'X':
                curr=10
            elif s[i]== 'L':
                curr=50
            elif s[i]== 'C':
                curr=100
            elif s[i]== 'D':
                curr=500
            elif s[i]== 'M':
                curr=1000

            result = result + curr

            if(pre<curr):
                result=result-2*pre
            pre = curr

        return result