Welcome 歡迎光臨! 愛上網路 - 原本退步是向前

羅馬數字轉阿拉伯數字 LeetCode 13

羅馬的計數系統是由七個不同的符號來代表下表,這套記數系統只要用來記數,卻不方便於四則演算。

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

4被寫作 IV,因為V前面的I被視為減去來構成4

Example 3:

Input: "IX"
Output: 9

9被寫作 IX,因為X前面的I被視為減去來構成9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

def RomantoInteger(instr):
    Roman={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
    result = 0;
    for s in range(len(instr)):
        if(Roman[instr[s]]):            
            temp = Roman[instr[s]];
            if(s != 0 and Roman[instr[s-1]] < Roman[instr[s]]):
                temp = temp - (Roman[instr[s-1]])*2;
            result = result + temp ;

    return  result;

 

DICT 轉換時KEY 和VALUE 問題,VALUE值如果為數值 不可用單引號或雙引值包起來

temp = temp - (Roman[instr[s-1]])*2; 前面已經加一次了所以要扣二次

方法二

def RomantoInteger2(instr):
    Roman={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
    result = 0
    i = 0
    tmp=0
    while i < len(instr):
        tmp = Roman[instr[i]];
        if (i + 1) < len(instr) and Roman[instr[i]] < Roman[instr[i + 1]]:
            tmp = Roman[instr[i + 1]] -Roman[instr[i]]
            i += 1
        i += 1
        result += tmp

    return  result

 

 

[ Python ] 瀏覽次數 : 36 更新日期 : 2024/07/28