Java 罗马数字到数字的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20313254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:00:08  来源:igfitidea点击:

Roman Numeral to Number Conversion

java

提问by user3003605

Trying to write program to read in a string of characters that represent a Roman numeral (from user input) and then convert it to Arabic form (an integer). For instance, I = 1, V = 5, X = 10 etc.

尝试编写程序以读取代表罗马数字的字符串(来自用户输入),然后将其转换为阿拉伯形式(整数)。例如,I = 1、V = 5、X = 10 等。

Basically, the constructor that takes a parameter of type String must interpret the string (from user input) as a Roman numeral and convert it to the corresponding int value.

基本上,采用 String 类型参数的构造函数必须将字符串(来自用户输入)解释为罗马数字并将其转换为相应的 int 值。

Is there an easier way to solve this besides the below in progress (which isn't compiling as yet):

除了以下正在进行的(尚未编译)之外,是否还有更简单的方法来解决此问题:

import java.util.Scanner;

public class RomInt {
String roman;
int val;
void assign(String k)
{
  roman=k;
}

private class Literal
{
    public char literal;
    public int value;

    public Literal(char literal, int value)
    {
        this.literal = literal;
        this.value = value;
    }
}

private final Literal[] ROMAN_LITERALS = new Literal[]
        {
                new Literal('I', 1),
                new Literal('V', 5),
                new Literal('X', 10),
                new Literal('L', 50),
                new Literal('C', 100),
                new Literal('D', 500),
                new Literal('M', 1000)
        };

public int getVal(String s) {

   int holdValue=0;

        for (int j = 0; j < ROMAN_LITERALS.length; j++)
        {
            if (s.charAt(0)==ROMAN_LITERALS[j].literal)
            {
                       holdValue=ROMAN_LITERALS[j].value;
                           break;
            }  //if()
        }//for()

  return holdValue;
}  //getVal()
public int count()
{
   int count=0;
   int countA=0;
   int countB=0;
   int lastPosition = 0;
    for(int i = 0 ; i < roman.length(); i++)
    {
      String s1 = roman.substring(i,i+1);
        int a=getVal(s1);
        countA+=a;
    }
    for(int j=1;j<roman.length();j++)
    {
        String s2=  roman.substring(j,j+1);
        String s3=  roman.substring(j-1,j);
        int b=getVal(s2);
        int c=getVal(s3);
        if(b>c)
        {
            countB+=c;
        }
    }
    count=countA-(2*countB);
    return count;
    }


void disp()
{

     int result=count();
    System.out.println("Integer equivalent of "+roman+" = " +result);
}


  public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt();

}

}  

回答by Masudul

Use enum, for easy and simple solution. At first define the decimal equivalent weight at roman.

使用enum, 以获得简单的解决方案。首先在罗马定义十进制当量。

enum Roman{
    i(1),iv(4),v(5), ix(9), x(10);
    int weight;

    private Roman(int weight) {
        this.weight = weight;
    }
};

This is the method to convert decimal to roman String.

这是将十进制转换为罗马字符串的方法。

static String decToRoman(int dec){
    String roman="";
    Roman[] values=Roman.values();
    for (int i = values.length-1; i>=0; i--) {
       while(dec>=values[i].weight){
           roman+=values[i];
           dec=dec-values[i].weight;
       }            
    }
    return roman;
}

回答by Alya'a Gamal

Roman numerals/Decode Example:

罗马数字/解码示例:

class Roman {

    private static int decodeSingle(char letter) {
        switch (letter) {
            case 'M':
                return 1000;
            case 'D':
                return 500;
            case 'C':
                return 100;
            case 'L':
                return 50;
            case 'X':
                return 10;
            case 'V':
                return 5;
            case 'I':
                return 1;
            default:
                return 0;
        }
    }

    public static int decode(String roman) {
        int result = 0;
        String uRoman = roman.toUpperCase(); //case-insensitive
        for (int i = 0; i < uRoman.length() - 1; i++) {//loop over all but the last character
            if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))) {
                result -= decodeSingle(uRoman.charAt(i));
            } else {
                result += decodeSingle(uRoman.charAt(i));
            }
        }
        result += decodeSingle(uRoman.charAt(uRoman.length() - 1));
        return result;
    }

    public static void main(String[] args) {
        System.out.println(decode("MCMXC")); //1990
        System.out.println(decode("MMVIII")); //2008
        System.out.println(decode("MDCLXVI")); //1666
    }
}

回答by Sameer Sawla

You can try using a Hashmap to store the roman numerals and equivalent arabic numerals.

您可以尝试使用 Hashmap 来存储罗马数字和等效的阿拉伯数字。

HashMap test = new HashMap();

HashMap 测试 = new HashMap();

test.add("I",1);
test.add("V",5);
test.add("X",10);
test.add("L",50);
test.add("C",100);
test.add("D",500);
test.add("M",1000);
//This would insert all the roman numerals as keys and their respective arabic numbers as 
  values.

To retrieve respective arabic numeral one the input of the user, you can use following peice of code:

要检索用户输入的相应阿拉伯数字之一,您可以使用以下代码:

Scanner sc = new Scanner(System.in);
System.out.println(one.get(sc.next().toUpperCase()));
//This would print the respective value of the selected key.This occurs in O(1) time.

Secondly,

其次,

If you only have these set of roman numerals, then you can go for simple switch case statement.

如果您只有这些罗马数字集,那么您可以使用简单的 switch case 语句。

switch(sc.next().toUpperCase())
{
case 'I' :
     System.out.println("1");
     break;
case 'V'
     System.out.println("5");
     break;
.
.
.
& so on 
}

Hope this helps.

希望这可以帮助。

回答by Blub

How about this:

这个怎么样:

public static int convertFromRoman(String roman) {
    Map<String, Integer> v = new HashMap<String, Integer>();
    v.put("IV", 4);
    v.put("IX", 9);
    v.put("XL", 40);
    v.put("CD", 400);
    v.put("CM", 900);
    v.put("C", 100);
    v.put("M", 1000);
    v.put("I", 1);
    v.put("V", 5); 
    v.put("X", 10);
    v.put("L", 50);
    v.put("D", 500);
    int result = 0;
    for (String s : v.keySet()) {
     result += countOccurrences(roman, s) * v.get(s);
     roman = roman.replaceAll(s, "");
    }

    return result;
}



public static int countOccurrences(String main, String sub) {
   return (main.length() - main.replace(sub, "").length()) / sub.length();
} 

Not sure I've got all possible combinations as I'm not an expert in roman numbers. Just make sure that the once where you substract come first in the map.

不确定我是否有所有可能的组合,因为我不是罗马数字的专家。只需确保您减去的地方在地图中排在第一位。

回答by Kishore

Your compilation issue can be resolved with below code. But surely its not optimized one:

您的编译问题可以通过以下代码解决。但肯定它不是优化的:

public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter Roman Symbol:");
    String s = keyboard.nextLine();

    RomInt temp = new RomInt();
    temp.getVal(s);
    temp.assign(s);
    temp.disp();
}