2022年9月28日 星期三

Leetcode 紀錄 - Roman numerals to integer

Roman numerals to integer 

需要將輸入羅馬數字後轉換成一般的阿拉伯數字

假設輸入的 Roman numerals 為 IV ,此時我們需要依序來處理每個字元,

重點在於羅馬數字計算的規則上第一個數字比下一個小的話就要拿來減去該值,

如 IV 分別表示 1 , 5 此時就等於 5 - 1,結果是 4。  

所以在程式處理上就直接先把第一個值加到 result 中,當處理下一個值的時候就拿來跟上一個值比,

較大的話就會進入 if 中,讓大去減小即可。

但也因為一開始直接將數值都直接加進 result 中,所以符合條件時要減去兩倍喔。

Python :

class Solution:
    def romanToInt(self ,s) -> int:
        roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        result = 0
        for index in range(len(s)) :
            if index > 0 and roman[s[index-1]] < roman[s[index]]:
                result += (roman[s[index]] - roman[s[index-1]]*2 )
            else :
                result += roman[s[index]]
        return result ;

沒有留言:

張貼留言