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;
}
this is very basic implementation of what you asked and working for all the test cases. If you find anything wrong in it than do mention it,i will try to make it correct also the code is in C++ .
Lets look at this problem with 3 different scenarios
When we see a pattern like the following
where all characters as the same: We add the value of each characters in the pattern
When we see any 2 consecutive characters different where first is smaller in value then the 2nd
We subtract the value of first from second e.g.
When we see a any 2 consecutive characters different where first is greater in value then the second
We add first and second e.g.
Now we can find the result if we do this recursively. Here is the java implementation :
Try this - It is simple and compact and works quite smoothly:
This
scala
solution might be useful:Here is my one...