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
>>>

沒有留言:

張貼留言

ModBus + Fuxa + MQTT

  ModBus + Fuxa + MQTT  這是一個非常實用且經典的工業物聯網(IIoT)與數據可視化架構。在這個架構中, Modbus Poll 負責模擬底層工業設備(如 PLC、感測器), MQTT Broker 擔任資料交換的中台,而 FUXA 則是一套開源的 W...