将罗马数字转换为整数

Dev*_*tep 3 java arrays loops

我正在关注的罗马数字到整数转换器:

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

我尝试将 Javascript 函数转换为 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);
}
Run Code Online (Sandbox Code Playgroud)

}

输出是615,这是不正确的。

请帮助我理解我哪里出错了。

Era*_*ran 5

test = test.replace(roman[i], "");将所有出现的“C”替换为“”,因此在找到第一个“C”并将总数加 100 后,您将消除所有剩余的“C”,并且从不计算它们。因此,您实际上计算了 的值"DCXV",即615

您应该只替换roman[i]起始索引为 0 的出现,您可以通过替换来实现:

test = test.replace(roman[i], "");
Run Code Online (Sandbox Code Playgroud)

和:

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

下列:

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);
Run Code Online (Sandbox Code Playgroud)

印刷:

895
Run Code Online (Sandbox Code Playgroud)