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;
}
what about this conversion. no switch, no case at all...
P.S. : I use this script from a bash shell
This should work:
Supposing Well-formed Roman numbers:
Since most of the answers here are in Java, I'm posting the answer in C++ (since I am bored right now and nothing more productive to do :) But please, no downvotes except if code is wrong. Known-issues = will not handle overflow
Code:
// test code
This is a modest variation of the recursive algorithm suggested by Sahtiel:
It uses less than 10 effective lines of code.
Solution using tail recursion:
Testing: