将罗马数字转换为整数

3

我正在使用的罗马数字转整数转换器:

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);
}

输出结果为615,这是错误的。

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

3个回答

6

你的test = test.replace(roman[i], "");会将所有出现的"C"都替换成空字符串""。所以当你找到第一个"C"并将100加到总数中后,你就消除了所有剩下的"C",并且永远不会再计算它们。因此,你实际上计算的是"DCXV"的值,即615

你应该只替换roman[i]的起始索引为0的那个出现次数,你可以通过以下方式实现:

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

使用:

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

以下内容:

以下是:

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);

打印:
895

1
这将替换每个出现的字符。相反,你应该仅截取字符串开头(位置0)处的出现。
尝试使用 substring 替代 replace,并将 roman[i] 的长度作为参数传递。

0

def value(r): if (r == 'I'): return 1 if (r == 'V'): return 5 if (r == 'X'): return 10 if (r == 'L'): return 50 if (r == 'C'): return 100 if (r == 'D'): return 500 if (r == 'M'): return 1000 return -1

def romanToDecimal(str): res = 0 i = 0

while (i < len(str)):

    # Getting value of symbol s[i]
    s1 = value(str[i])

    if (i + 1 < len(str)):

        # Getting value of symbol s[i + 1]
        s2 = value(str[i + 1])

        # Comparing both values
        if (s1 >= s2):

            # Value of current symbol is greater
            # or equal to the next symbol
            res = res + s1
            i = i + 1
        else:

            # Value of current symbol is greater
            # or equal to the next symbol
            res = res + s2 - s1
            i = i + 2
    else:
        res = res + s1
        i = i + 1

为什么你要使用Python代码来回答一个Java问题? 此外,请使用反引号(backticks)来包装你的整个代码块。 请确保给出一个简短的解释,而不仅仅是一大堆代码。 - Vincent C.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接