2017年12月19日 星期二

a013-2羅馬數字轉換成阿拉伯數字

a013-2 羅馬數字轉換成阿拉伯數字
Roman to integer
給出一個羅馬數字(字串),返回此數位的阿拉伯數字(int)
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.


# 羅馬數字轉數字
#Given a roman numeral, convert it to an integer.
#Input is guaranteed to be within the range from 1 to 3999.

def romanToInt(s):
    """
    :type s: str
    :rtype: int
    """
    a = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
    sum = 0
    for i in range(len(s) - 1): #range右邊界len(s) - 1 保證 i + 1不會下標越界
        if a[s[i]] < a[s[i+1]]:
            sum -= a[s[i]]
        else:
            sum += a[s[i]]
    return sum + a[s[len(s) - 1]]



print ("羅馬數字轉10進制")
strX=str(input("請輸入羅馬數字 :"))
print()
print(romanToInt(strX))

   

===================== RESTART: D:/Python_APSC/a013-2.py =====================
羅馬數字轉10進制
請輸入羅馬數字 :CCCLXXXIX

389
>>>
===================== RESTART: D:/Python_APSC/a013-2.py =====================
羅馬數字轉10進制
請輸入羅馬數字 :MMXC

2090
>>>
===================== RESTART: D:/Python_APSC/a013-2.py =====================
羅馬數字轉10進制
請輸入羅馬數字 :MXCII

1092
>>>

沒有留言:

張貼留言

WOKWI ESP32 LED Control , Node-Red MQTT SQLITE  

WOKWI ESP32 LED Control ,  Node-Red  MQTT SQLITE   const char broker[] = "test.mosquitto.org" ; //const char broker[] = "br...