gpt4 book ai didi

javascript - JS中的罗马到整数为什么它只转换第一个字符

转载 作者:行者123 更新时间:2023-11-29 16:37:40 24 4
gpt4 key购买 nike

我尝试解决 Leedcode 问题 13,问题是给定一个罗马数字,将其转换为整数。(输入保证在 1 到 3999 的范围内。)这是我下面的代码,我想知道为什么它只将罗马数字中的第一个字符转换为整数?

var romanToInt = function(s) {
var result = 0;
if (s == null) {
result = 0;
}
var myMap = new Map();
myMap.set('I', 1);
myMap.set('V', 5);
myMap.set('X', 10);
myMap.set('L', 50);
myMap.set('C', 100);
myMap.set('D', 500);
myMap.set('M', 1000);

var len = s.length;
for (var i = 0; i < len; i++) {
if (myMap.get(s.charAt(i)) < myMap.get(s.charAt(i + 1))) {
result -= myMap.get(s.charAt(i))
} else {
result += myMap.get(s.charAt(i))
}
return result;
};
}

console.log(romanToInt('VI'));
console.log(romanToInt('V'));
console.log(romanToInt('VII'));

最佳答案

因为

return result;

在一次迭代后结束循环。将其向下移动一行。而且,如果您进行适当的格式化,则根本不会犯此类错误;)

const values = new Map([
['I', 1],
['V', 5],
['X', 10]
/*....*/
]);

function romanToInt(string) {
let result = 0,
current, previous = 0;
for (const char of string.split("").reverse()) {
current = values.get(char);
if (current >= previous) {
result += current;
} else {
result -= current;
}
previous = current;
}
return result;
}

console.log(romanToInt('I'));
console.log(romanToInt('II'));
console.log(romanToInt('III'));
console.log(romanToInt('IV'));
console.log(romanToInt('V'));
console.log(romanToInt('VI'));
console.log(romanToInt('VII'));
console.log(romanToInt('VIII'));
console.log(romanToInt('IX'));
console.log(romanToInt('X'));
console.log(romanToInt('XI'));
console.log(romanToInt('XII'));
console.log(romanToInt('XIII'));
console.log(romanToInt('XIV'));
console.log(romanToInt('XV'));
console.log(romanToInt('XVI'));
console.log(romanToInt('XVII'));
console.log(romanToInt('XVIII'));
console.log(romanToInt('XIX'));
console.log(romanToInt('XX'));

关于javascript - JS中的罗马到整数为什么它只转换第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659711/

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