嗨,我正在尝试使用 javascript 将罗马数字转换为阿拉伯数字。我写了一个代码,但它失败了。我试图遵循的规则是:
如果较大的数字在较小的数字之前,则加法,如果较小的数字在较大的数字之前,则减法。
除此之外,我还有一些其他规则,例如 'D'、'L' 和 'V' 根本不能重复,而 'M' 只能重复两次(不确定如何实现,我可以使用正则表达式吗?为它以及如何?)
代码 :
function romanToArabic(roman){
if(roman == null)
return -1;
var value;
for(var i=0;i<roman.length;i++){
current = char_to_int(roman.charAt(i));
next = char_to_int(roman.charAt(i+1));
console.log("Current",current);
console.log("Next",next);
if(current >= next){
value = current + next;
console.log(value);
}
else {
console.log(value);
value = next - current;
}
}
return value;
}
function char_to_int(character) {
switch(character){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
console.log(romanToArabic('IIX'));
有人可以帮忙吗?会很感激的!
添加了截图:
The issue is that your code only subtracts the value corresponding to one character, while in IIX
you need to subtract twice (although that kind of representation for the number 8 is quite unconventional -- 8 would normally be represented as VIII
).
The solution is to keep collecting a separate sum for when the symbol is the same, so that after reading the first two "I", you have two separate sums:
Then when you encounter the "X" and detect that a subtraction is needed, you first undo the addition already done for the grand total, and then perform the subtraction with the value you collected for the "I":
After this, you start with a reset value for "X":
这是您为发生这种情况而改编的代码:
function romanToArabic(roman){
if(roman == null)
return -1;
var totalValue = 0,
value = 0, // Initialise!
prev = 0;
for(var i=0;i<roman.length;i++){
var current = char_to_int(roman.charAt(i));
if (current > prev) {
// Undo the addition that was done, turn it into subtraction
totalValue -= 2 * value;
}
if (current !== prev) { // Different symbol?
value = 0; // reset the sum for the new symbol
}
value += current; // keep adding same symbols
totalValue += current;
prev = current;
}
return totalValue;
}
function char_to_int(character) {
switch(character){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
console.log(romanToArabic('IIX'));
至于您将连续“I”的数量限制为最多两个,“D”最多为一个的附加问题,...您可以在函数的开头使用正则表达式测试:
if (/III|XXX|CCC|MMM|VV|LL|DD|[^IVXLCDM]/.test(roman))
return -1;
您可以附加由|
. 例如,如果您不希望“I”直接出现在“L”、“C”、“D”或“M”之前,则扩展为:
if (/III|XXX|CCC|MMM|VV|LL|DD|[^IVXLCDM]|I[LCDM]/.test(roman))
return -1;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句