📌  相关文章
📜  用于将罗马数字转换为 1 到 3999 之间的十进制数字的Java程序

📅  最后修改于: 2022-05-13 01:56:06.084000             🧑  作者: Mango

用于将罗马数字转换为 1 到 3999 之间的十进制数字的Java程序

给定一个罗马数字,任务是找到它对应的十进制值。

例子 :

Input: IX
Output: 9
IX is a Roman symbol which represents 9 

Input: XL
Output: 40
XL is a Roman symbol which represents 40

Input: MCMIV
Output: 1904
M is a thousand, 
CM is nine hundred and 
IV is four

罗马数字基于以下符号。

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

方法:罗马数字中的数字是由这些符号组成的字符串,按降序排列(例如,M 在前,然后是 D,等等)。但是,在少数特定情况下,为避免四个字符连续重复(如 IIII 或 XXXX),通常使用减法符号如下:

  • 放在VX之前表示少一,所以四是IV (比 5 少一),而 9 是 IX(比 10 少一)。
  • 放在LC之前的X表示少十个,所以XL是四十(10 比 50 少),90 是XC (十比一百少)。
  • C放在DM前面表示少一百,所以四百是CD (一百少于五百),九百是CM (一百少于一千)。

将罗马数字转换为整数的算法:

  1. 将罗马数字字符串拆分为罗马符号(字符)。
  2. 将罗马数字的每个符号转换成它所代表的值。
  3. 从索引 0 开始,一个一个地取符号:
    1. 如果符号的当前值大于或等于下一个符号的值,则将此值添加到运行总计中。
    2. 否则通过将下一个符号的值添加到运行总数中来减去该值。

以下是上述算法的实现:

Java
// Java Program to convert Roman
// Numerals to Numbers
import java.util.*;
 
public class RomanToNumber
{
    // This function returns
    // value of a Roman symbol
    int value(char r)
    {
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
 
    // Finds decimal value of a
    // given romal numeral
    int romanToDecimal(String str)
    {
        // Initialize result
        int res = 0;
 
        for (int i = 0; i < str.length(); i++)
        {
            // Getting value of symbol s[i]
            int s1 = value(str.charAt(i));
 
            // Getting value of symbol s[i+1]
            if (i + 1 < str.length())
            {
                int s2 = value(str.charAt(i + 1));
 
                // Comparing both values
                if (s1 >= s2)
                {
                    // Value of current symbol
                    // is greater or equalto
                    // the next symbol
                    res = res + s1;
                }
                else
                {
                    // Value of current symbol is
                    // less than the next symbol
                    res = res + s2 - s1;
                    i++;
                }
            }
            else
            {
                res = res + s1;
            }
        }
 
        return res;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        RomanToNumber ob = new RomanToNumber();
 
        // Considering inputs given are valid
        String str = "MCMIV";
        System.out.println(
        "Integer form of Roman Numeral" +
        " is " + ob.romanToDecimal(str));
    }
}


Java
// Java Program to convert Roman
// Numerals to Numbers
import java.util.Map;
import java.util.HashMap;
class GFG{
     
private static final Map roman = new HashMap()
{{
    put('I', 1);
    put('V', 5);
    put('X', 10);
    put('L', 50);
    put('C', 100);
    put('D', 500);
    put('M', 1000);
}};
 
// This function returns value
// of a Roman symbol
private static int romanToInt(String s)
{
    int sum = 0;
    int n = s.length();
     
    for(int i = 0; i < n; i++)
    {       
        // If present value is less than
        // next value, subtract present
        // from next value and add the
        // resultant to the sum variable.
        if (i != n - 1 &&
            roman.get(s.charAt(i)) <
            roman.get(s.charAt(i + 1)))
        {
            sum += roman.get(s.charAt(i + 1)) -
                   roman.get(s.charAt(i));
            i++;
        }
        else
        {
            sum += roman.get(s.charAt(i));
        }
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{   
    // Considering inputs given are valid
    String input = "MCMIV";
     
    System.out.print(
    "Integer form of Roman Numeral is " +
     romanToInt(input));
}
}
// This code is contributed by rahuldevgarg



输出:

Integer form of Roman Numeral is 1904

复杂性分析:

  • 时间复杂度: O(n),其中 n 是字符串的长度。
    只需要遍历一次字符串。
  • 空间复杂度: O(1)。
    因为不需要额外的空间。

另一种解决方案——

Java

// Java Program to convert Roman
// Numerals to Numbers
import java.util.Map;
import java.util.HashMap;
class GFG{
     
private static final Map roman = new HashMap()
{{
    put('I', 1);
    put('V', 5);
    put('X', 10);
    put('L', 50);
    put('C', 100);
    put('D', 500);
    put('M', 1000);
}};
 
// This function returns value
// of a Roman symbol
private static int romanToInt(String s)
{
    int sum = 0;
    int n = s.length();
     
    for(int i = 0; i < n; i++)
    {       
        // If present value is less than
        // next value, subtract present
        // from next value and add the
        // resultant to the sum variable.
        if (i != n - 1 &&
            roman.get(s.charAt(i)) <
            roman.get(s.charAt(i + 1)))
        {
            sum += roman.get(s.charAt(i + 1)) -
                   roman.get(s.charAt(i));
            i++;
        }
        else
        {
            sum += roman.get(s.charAt(i));
        }
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{   
    // Considering inputs given are valid
    String input = "MCMIV";
     
    System.out.print(
    "Integer form of Roman Numeral is " +
     romanToInt(input));
}
}
// This code is contributed by rahuldevgarg


输出:

Integer form of Roman Numeral is 1904

时间复杂度– O(N)
辅助空间- O(1)

有关详细信息,请参阅有关将罗马数字转换为 1 到 3999 之间的十进制的完整文章!