Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert roman numeral to integer

Tags:

java

arrays

loops

The roman numeral to integer converter I am following:

https://www.selftaughtjs.com/algorithm-sundays-converting-roman-numerals/

My attempt at converting the Javascript function to Java:

public class RomanToDecimal {
public static void main (String[] args) {

    int result = 0;
    int[] decimal = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    // Test string, the number 895
    String test = "DCCCXCV";

    for (int i = 0; i < decimal.length; i++ ) {
        while (test.indexOf(roman[i]) == 0) {
            result += decimal[i];
            test = test.replace(roman[i], "");
        }
    }
    System.out.println(result);
}

}

The output is 615, which is incorrect.

Please help me understand where I went wrong.

like image 571
Dev Step Avatar asked Oct 20 '25 14:10

Dev Step


2 Answers

Your test = test.replace(roman[i], ""); replaces all occurrences of "C" with "", so after you find the first "C" and add 100 to the total, you eliminate all the remaining "C"s, and never count them. Therefore you actually compute the value of "DCXV", which is 615.

You should only replace the occurrence of roman[i] whose start index 0, which you can achieve by replacing:

test = test.replace(roman[i], "");

with:

test = test.substring(roman[i].length()); // this will remove the first 1 or 2 characters
                                          // of test, depending on the length of roman[i]

The following:

int result = 0;
int[] decimal = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

// Test string, the number 895
String test = "DCCCXCV";

for (int i = 0; i < decimal.length; i++ ) {
    while (test.indexOf(roman[i]) == 0) {
        result += decimal[i];
        test = test.substring(roman[i].length());
    }
}
System.out.println(result);

prints:

895
like image 161
Eran Avatar answered Oct 22 '25 04:10

Eran


test = test.replace(roman[i], "");

This will replace every occurrence. Instead, you should only truncate off the occurrence at the beginning of the string (position 0).

Try using substring instead of replace, and pass as an argument the length of roman[i]

like image 23
Patrick Parker Avatar answered Oct 22 '25 04:10

Patrick Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!