I had an interview in which I am terrible. So now I am trying to find a solution to the issue. Here is the interview question:
"We have the following mapping:
M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1.
And we have the following rules:
Each letter represents a positive integer value.
You add values โโtogether except ...
... when a value (or the same values โโare executed) is accompanied by a large value, you subtract the total amount of this run of values.
Examples:
IIX โ 8
MCCMIIX โ 1808
We are given this Java method: int valueOfRoman(char roman) . We implement the Java method: int romanToInt(String s) "
I know that this is not the correct Roman number system, but it really is a question.
I managed to program the working solution on the correct Roman system. But I cannot change it so that it adapts to these new rules, in particular to rule 3. I tried, but to no avail. The way my solution right now, for IIX, it prints 10 instead of the correct answer 8. Here is my code (I also implemented valueOf for my testing):
static int romanToInt(String s) { char curr; int currVal; char prev; int prevVal; int total = valueOfRoman(s.charAt(0)); for (int i = 1; i < s.length(); i++) { curr = s.charAt(i); currVal = valueOfRoman(curr); prev = s.charAt(i-1); prevVal = valueOfRoman(prev); total += currVal; if(currVal > prevVal) { total = total - (2*prevVal); } } return total; } static int valueOfRoman(char c) { if (c == 'M') { return 1000; } else if (c == 'D') { return 500; } else if (c == 'C') { return 100; } else if (c == 'L') { return 50; } else if (c == 'X') { return 10; } else if (c == 'V') { return 5; } else if (c == 'I') { return 1; } return -1; }
Any help really appreciated. It would be especially helpful if you could tell me how to change my code. Thanks!
EDIT: I edited the names of the methods to make them clearer.
java string algorithm roman-numerals
user224567893
source share