为了账号安全,请及时绑定邮箱和手机立即绑定

将罗马数字转换为整数

将罗马数字转换为整数

饮歌长啸 2021-06-21 08:10:13
我正在关注的罗马数字到整数转换器: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,这是不正确的。请帮助我理解我哪里出错了。
查看完整描述

2 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

您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


查看完整回答
反对 回复 2021-06-23
?
12345678_0001

TA贡献1802条经验 获得超5个赞

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

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

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


查看完整回答
反对 回复 2021-06-23
  • 2 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信