【问题标题】:Convert roman numeral to integer将罗马数字转换为整数
【发布时间】:2019-01-09 20:33:05
【问题描述】:

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

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,不正确。

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

【问题讨论】:

    标签: java arrays loops


    【解决方案1】:

    您的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
    

    【讨论】:

      【解决方案2】:

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

      这将替换每一个出现。相反,您应该只截断字符串开头(位置 0)的出现。

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

      【讨论】:

        猜你喜欢
        • 2011-10-25
        • 2012-10-09
        • 1970-01-01
        • 2020-05-11
        • 2021-12-15
        • 2014-10-19
        • 2014-03-04
        相关资源
        最近更新 更多