繁体   English   中英

将罗马数字转换为integer

[英]Convert roman numeral to integer

罗马数字到 integer 转换器我在下面:

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

我尝试将 Javascript function 转换为 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);
}

}

output 是615 ,这是不正确的。

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

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

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

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

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

这将取代每次出现。 相反,您应该只截断字符串开头的位置(位置0)。

尝试使用substring而不是replace,并作为参数传递roman[i]的长度

def value(r): if (r == 'I'): 返回 1 if (r == 'V'): 返回 5 if (r == 'X'): 返回 10 if (r == 'L' ): 返回 50 如果 (r == 'C'): 返回 100 如果 (r == 'D'): 返回 500 如果 (r == 'M'): 返回 1000 返回 -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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM