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


羅馬數字是基於古羅馬數字系統的一種數字表示法。字母M、D、C、L、X、V和I分別代表1000、500、100、50、10、5和1,我們將在下面的小節中討論所有主要的符號。在這個問題中,我們得到一個羅馬數字字串,我們的任務是將1到3999範圍內的羅馬數字轉換為十進位制。

讓我們看看下面的例子和解釋,以便更好地理解這個問題。

輸入1

str = "MCMIX"

輸出1

1909

解釋

M是1000的羅馬錶示法,

CM是900的羅馬錶示法,

IX是9的羅馬錶示法。

輸入2

str = "IV"

輸出

2

解釋

IV是4的羅馬錶示法。

輸入3

str = "VI"

輸出3

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

方法

我們已經看到了上面給定羅馬數字字串的例子,讓我們來看一下方法。

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

  • I出現在V或X之前表示少一。

    例如:4 = IV(比五少一),

    9 = IX(比十少一)

  • X出現在L或C之前表示少十。

    例如:40 = XL(比五十少十),

    90 = XC(比一百少十)

  • C出現在D和M之前表示少一百

    例如:400 = CD(比五百少一百)

    900 = CM(比一千少一百)

讓我們看看下面的程式碼,以便更好地理解上述方法。

例子

下面是一個Java程式,用於將1到3999之間的羅馬數字轉換為十進位制。

import java.util.*;

// Create a class for initializing the function to return the Roman symbol's value.
public class Solution{
   // This function is created to return a Roman symbol's value.
   int romanValue(char ch)    {
      if(ch=='I')
         return 1;
      else if(ch=='V')
         return 5;
      else if(ch=='X')
         return 10;
      else if(ch=='L')
         return 50;
      else if(ch=='C')
         return 100;
      else if(ch=='D')
         return 500;
      else if(ch=='M')
         return 1000;
      return -1;
   } 
   
   // This function is created for the conversion of Roman numerals to decimal numerals
   int convertRomanToDecimal(String str) {
      // Initialize decimal value 
      int decVal = 0;
      int n = str.length(); // Getting the size of the string
      for (int i = 0; i < n; i++) {
         // check if i+1 charchter exist and getting value of roman symbol str[i] and str[i+1]
         if (i + 1 < n && romanValue(str.charAt(i)) < romanValue(str.charAt(i + 1)))  {
            //subtract the current value from the next value and add the decVal variable
            decVal = decVal + romanValue(str.charAt(i + 1)) - romanValue(str.charAt(i));
            i++; // Increment the index of the string to point to the next char
         }
         // If i+1 char not exist
         else {
            decVal = decVal + romanValue(str.charAt(i)); // add the first char value
         }
      } 
      return decVal; // Return decimal value
   } 
   public static void main(String args[]) {
      Solution ob = new Solution(); 
      String str = "MCMIX"; // Given string
      System.out.println("Roman Numeral: " + str);
      // Print the decimal form and call the function of conversion
      System.out.println("The decimal Numeral form of the Roman Numeral" + " is " + ob.convertRomanToDecimal(str));
   }
}

輸出

Roman Numeral: MCMIX
The decimal Numeral form of the Roman Numeral is 1909

時間和空間複雜度

上述程式碼的時間複雜度為O(N),因為只需要遍歷一次字串。其中N是給定羅馬數字字串的大小。由於沒有使用額外的空間,所以上述程式碼的空間複雜度為O(1)。

另一種使用雜湊表的方法

例子

import java.util.Map;
import java.util.HashMap;
public class Solution {
   public static final Map<Character,
      Integer> romanValue = new HashMap<Character,
   Integer>() {
      {
         put ( 'M', 1000 );
         put ( 'D', 500 );
         put ( 'C', 100 );
         put ( 'L', 50 );
         put ( 'X', 10 );
         put ( 'V', 5 );
         put ( 'I', 1 );
      }
   };
   // Function is created for conversion of the Roman numeral to decimal numeral
   private static int convertRomanToDecimal(String str) {
      // Initialize decimal value
      int decVal = 0;
      for (int i = 0; i < str.length(); i++) {
         // store numeric value of roman symbol str[i]
         int first = romanValue.get(str.charAt(i));
         // check if i+1 charchter exist or not
         if (i + 1 < str.length()) {
            // store numeric value of roman symbol str[i+1]
            int second = romanValue.get(str.charAt(i + 1));
            // check which value is greater first or second
            if (first <= second) {
               // if first value <= second add first value to variable decVal
               decVal = decVal + first;
            } else  {
               // Value of first char is less than to the the second char
               decVal = decVal + second - first;
               i++; // Increment the index of string to point to next char
            }
         }
         // If i+1 char not exist
         else {
            decVal = decVal + first; // add the first char value
         }
      }
      return decVal; // Return decimal value
   }
   public static void main(String args[]) {
      String str = "MMMIX"; // Given string
      System.out.println("Roman Numeral: " + str);
      // print the decimal form and call function of conversion
      System.out.println("Decimal Numeral form of Roman Numeral" +
         " is " + convertRomanToDecimal(str));
    }
}

輸出

Roman Numeral: MMMIX
Decimal Numeral form of Roman Numeral is 3009

結論

在本教程中,我們實現了一個Java程式,用於將1到3999之間的羅馬數字轉換為十進位制。我們用兩種方法實現了這個程式。第一種是普通函式,第二種是雜湊表函式。

更新於:2023年7月11日

421 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告