gpt4 book ai didi

java - 将罗马数字转换为整数

转载 作者:行者123 更新时间:2023-12-04 20:46:10 24 4
gpt4 key购买 nike

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

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

请帮助我了解哪里出了问题。

最佳答案

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

关于java - 将罗马数字转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51647368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com