2 回答
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
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
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
TA贡献1802条经验 获得超5个赞
test = test.replace(roman[i], "");
这将替换每次出现。相反,您应该只截断字符串开头(位置 0)的出现。
尝试使用substring
而不是替换,并将长度作为参数传递roman[i]
添加回答
举报