Python程式:將1到3999之間的羅馬數字轉換為十進位制


羅馬數字是基於羅馬數字系統的一種數字表示法中使用的字元。所有主要符號都在以下部分中介紹。在本問題中,我們得到一個羅馬數字字串,我們的任務是將範圍為1到3999的羅馬數字轉換為十進位制。

以下是一些示例和解釋,以幫助您更好地理解問題。

輸入

str = “MXCIX”

輸出

1099

解釋

M是1000的羅馬數字表示。

XC是90的羅馬數字表示。

IX是9的羅馬數字表示。

輸入

str = "II"

輸出

2

解釋

II是2的羅馬數字表示。

輸入

str = “XL”

輸出

40

解釋

XL是40的羅馬數字表示。

在討論方法之前,讓我們先看看主要的羅馬數字符號。羅馬數字完全基於以下符號:

符號
M 1000
CM 900
D 500
CD 400
C 100
XC 90
L 50
XL 40
X 10
IX 9
V 5
IV 4
I 1

方法

根據觀察,羅馬數字符號遵循降序來表示數字(例如,M排在首位,然後是C等)。但是,在某些情況下,它也遵循減法表示法,以防止連續重複四個字元(例如CCCC)。

  • I出現在X或V之前表示少一。-> 4用羅馬數字表示為IV(比五少一),-> 9用羅馬數字表示為IX(比十少一)

  • X出現在C或L之前表示少十。-> 40用羅馬數字表示為XL(比五十少十),-> 90用羅馬數字表示為XC(比一百少十)

  • C出現在M和D之前表示少一百 -> 400用羅馬數字表示為CD(比五百少一百)-> 900用羅馬數字表示為CM(比一千少一百)

為了進一步理解上述方法,讓我們看看下面的程式碼。

示例

Python程式:將1到3999之間的羅馬數字轉換為十進位制。

# Function is created to return a Roman symbol's value.
def value(ch):
   val = -1
   if(ch=='I'):
      val = 1
   if(ch=='V'):
      val = 5
   if(ch=='X'):
      val = 10
   if(ch=='L'):
      val = 50
   if(ch=='C'):
      val = 100
   if(ch=='D'):
      val = 500
   if(ch=='M'):
      val = 1000
   return val
def convertRomanToDecimal(str):
   decVal = 0
   i = 0
   n = len(str) # store the size of the string 
   while (i < n): 
      # store the numeric value of roman value str[i]
       current = value(str[i])
 
      # Check if i+1 charchter exists or not
       if (i + 1 < n): 
         # store the numeric value of roman value str[i+1]
         next = value(str[ i + 1 ]) 
         # Check which value is greater current or next
         if (current >= next): 
            # If current >= next add current
            # value to the variable decVal
            decVal = decVal + current
            # Increment the index of the string to point to the next char
            i = i + 1
         else:
            # If current<next add difference of next to current to the variable decVal
            decVal = decVal + next - current
            # Increment the index of the string to point to the next char
            i = i + 2
       else:
          decVal = decVal + current
          # Increment the index of the string to point to the next char
          i = i + 1 
   return decVal
print("The decimal Numeral form of the Roman Numeral is"),
print(convertRomanToDecimal("MXCIX"))

輸出

The decimal Numeral form of the Roman Numeral is
1099

時間和空間複雜度

上述程式碼的時間複雜度為O(N),其中N是字串的長度。由於程式碼中沒有使用額外的空間,因此上述程式碼的空間複雜度為O(1)。

方法2

在這種方法中,我們使用內建模組Roman直接將羅馬數字轉換為十進位制。為此,只需要使用pip安裝Roman模組。

pip install roman

成功安裝roman模組後,可以使用fromRoman()方法進行羅馬數字到十進位制的轉換。

它接收羅馬數值作為引數,並輸出十進位制數字。

示例

下面是一個Python程式,使用上述方法將羅馬數字轉換為十進位制。

import roman
egFirst = roman.fromRoman("MXCIX")
egSecond = roman.fromRoman("II")
egThird = roman.fromRoman("XL")
print("Roman to Decimal conversions are:")
print(egFirst)
print(egSecond)
print(egThird)

輸出

Roman to Decimal conversions are:
1099
2
40

方法3

這裡使用're'模組。這種方法的思想很簡單,我們在這裡使用Python的字典函式,將羅馬數字與其對應的十進位制值關聯起來。該程式接受羅馬數字作為輸入,並將其轉換為對應的十進位制值。

示例

# Python Program to convert Roman Numerals to Decimal
import re
# Given string of Roman value
strRoman = 'MXCIX' 
# putting Roman numerals and their associated values in a dictionary
romanValue = {'M':1000, 'X':10, 'L':50, 'V':5, 'C':100, 'D':500, 'I':1} 
# Creating the variable decValue and assign zero to it
decValue = 0
n = len(strRoman) 
# Adding each value from the Roman Numeral string through a loop to the decValue variable
for i in range(n):
   if i > 0 and romanValue[strRoman[i]] >romanValue[strRoman[i-1]]:
      decValue += romanValue[strRoman[i]] - 2 * romanValue[strRoman[i-1]]
   else:
      decValue += romanValue[strRoman[i]] 
# Printing the Roman numeral in decimal form
print("The decimal Numeral form of the Roman Numeral", strRoman, "is")
print(decValue)

輸出

The decimal Numeral form of the Roman Numeral MXCIX is
1099

結論

在本教程中,我們實現了一個Python程式,用於將1到3999之間的羅馬數字轉換為十進位制。我們實現了三種方法。第一種是使用普通函式,第二種是使用Roman模組,第三種是使用re模組(使用字典)。

更新於:2023年7月11日

瀏覽量:375

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.