Converting Roman Numerals To Decimal

2019-01-01 15:54发布

I have managed to get my code to convert most Roman numerals to its appropriate decimal value. But it doesn't work for some exceptional cases. Example : XCIX = 99 but my code prints 109.

Here is my code.

public static int romanConvert(String roman)
{
    int decimal = 0;

    String romanNumeral = roman.toUpperCase();
    for(int x = 0;x<romanNumeral.length();x++)
    {
        char convertToDecimal = roman.charAt(x);

        switch (convertToDecimal)
        {
        case 'M':
            decimal += 1000;
            break;

        case 'D':
            decimal += 500;
            break;

        case 'C':
            decimal += 100;
            break;

        case 'L':
            decimal += 50;
            break;

        case 'X':
            decimal += 10;
            break;

        case 'V':
            decimal += 5;
            break;

        case 'I':
            decimal += 1;
            break;
        }
    }
    if (romanNumeral.contains("IV"))
    {
        decimal-=2;
    }
    if (romanNumeral.contains("IX"))
    {
        decimal-=2;
    }
    if (romanNumeral.contains("XL"))
    {
        decimal-=10;
    }
    if (romanNumeral.contains("XC"))
    {
        decimal-=10;
    }
    if (romanNumeral.contains("CD"))
    {
        decimal-=100;
    }
    if (romanNumeral.contains("CM"))
    {
        decimal-=100;
    }
    return decimal;
}

标签: java
26条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 16:15

It will be good if you traverse in reverse.

public class RomanToDecimal {
    public static void romanToDecimal(java.lang.String romanNumber) {
        int decimal = 0;
        int lastNumber = 0;
        String romanNumeral = romanNumber.toUpperCase();
        /* operation to be performed on upper cases even if user 
           enters roman values in lower case chars */
        for (int x = romanNumeral.length() - 1; x >= 0 ; x--) {
            char convertToDecimal = romanNumeral.charAt(x);

            switch (convertToDecimal) {
                case 'M':
                    decimal = processDecimal(1000, lastNumber, decimal);
                    lastNumber = 1000;
                    break;

                case 'D':
                    decimal = processDecimal(500, lastNumber, decimal);
                    lastNumber = 500;
                    break;

                case 'C':
                    decimal = processDecimal(100, lastNumber, decimal);
                    lastNumber = 100;
                    break;

                case 'L':
                    decimal = processDecimal(50, lastNumber, decimal);
                    lastNumber = 50;
                    break;

                case 'X':
                    decimal = processDecimal(10, lastNumber, decimal);
                    lastNumber = 10;
                    break;

                case 'V':
                    decimal = processDecimal(5, lastNumber, decimal);
                    lastNumber = 5;
                    break;

                case 'I':
                    decimal = processDecimal(1, lastNumber, decimal);
                    lastNumber = 1;
                    break;
            }
        }
        System.out.println(decimal);
    }

    public static int processDecimal(int decimal, int lastNumber, int lastDecimal) {
        if (lastNumber > decimal) {
            return lastDecimal - decimal;
        } else {
            return lastDecimal + decimal;
        }
    }

    public static void main(java.lang.String args[]) {
        romanToDecimal("XIV");
    }
}
查看更多
查无此人
3楼-- · 2019-01-01 16:16
// Author: Francisco Edmundo
private int translateNumber(String texto) {
    int n = 0;
    int numeralDaDireita = 0;
    for (int i = texto.length() - 1; i >= 0; i--) {
        int valor = (int) translateNumber(texto.charAt(i));
        n += valor * Math.signum(valor + 0.5 - numeralDaDireita);
        numeralDaDireita = valor;
    }
    return n;
}
private double translateNumber(char caractere) {
    return Math.floor(Math.pow(10, "IXCM".indexOf(caractere))) + 5 * Math.floor(Math.pow(10, "VLD".indexOf(caractere)));
}
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 16:16

How about this?

int getdec(const string& input)
{
  int sum=0; char prev='%';
  for(int i=(input.length()-1); i>=0; i--)
  {
    if(value(input[i])<sum && (input[i]!=prev))
    {       sum -= value(input[i]);
            prev = input[i];
    }
    else
    {
            sum += value(input[i]);
            prev = input[i];
    }
  }
  return sum;
}
查看更多
低头抚发
5楼-- · 2019-01-01 16:17

Less code, more efficient. Not so clearer, sorry!

public int evaluateRomanNumerals(String roman) {
    return (int) evaluateNextRomanNumeral(roman, roman.length() - 1, 0);
}

private double evaluateNextRomanNumeral(String roman, int pos, double rightNumeral) {
    if (pos < 0) return 0;
    char ch = roman.charAt(pos);
    double value = Math.floor(Math.pow(10, "IXCM".indexOf(ch))) + 5 * Math.floor(Math.pow(10, "VLD".indexOf(ch)));
    return value * Math.signum(value + 0.5 - rightNumeral) + evaluateNextRomanNumeral(roman, pos - 1, value);
}
查看更多
梦该遗忘
6楼-- · 2019-01-01 16:17
        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);
    }

}  //RomInt---BLC
查看更多
唯独是你
7楼-- · 2019-01-01 16:17

Just got it working in Java, nice job guys.

    public int getDecimal (String roman) {
        int decimal = 0;
        int romanNumber = 0;
        int prev = 0;
        for (int i = roman.length()-1; i >= 0; i--){
            romanNumber = hashRomans.get(roman.charAt(i));
            if(romanNumber < decimal && romanNumber != prev ){
                decimal -= romanNumber;
                prev = romanNumber;
            } else {
                decimal += romanNumber;
                prev = romanNumber;
            }
        } 
        return decimal;
    }
查看更多
登录 后发表回答