将罗马数字转换为整数

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


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


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


饮歌长啸
浏览 167回答 2
2回答

汪汪一只猫

您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&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 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 895String test = "DCCCXCV";for (int i = 0; i < decimal.length; i++ ) {&nbsp; &nbsp; while (test.indexOf(roman[i]) == 0) {&nbsp; &nbsp; &nbsp; &nbsp; result += decimal[i];&nbsp; &nbsp; &nbsp; &nbsp; test = test.substring(roman[i].length());&nbsp; &nbsp; }}System.out.println(result);印刷:895

12345678_0001

test = test.replace(roman[i], "");这将替换每次出现。相反,您应该只截断字符串开头(位置 0)的出现。尝试使用substring而不是替换,并将长度作为参数传递roman[i]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java