Tengo dos soluciones para roman to integer en javascript ( enlace leetcode ), donde la primera no funciona y la segunda sí. Lo extraño es que no puedo notar ninguna diferencia entre los dos. Estoy seguro de que me estoy perdiendo algo, pero no puedo decirlo.
Aquí está el código sandbox No puedo decir por qué la función romanToInt no funciona mientras que romanToInt2 sí.
var romanToInt = function(s) { //create a map of roman numeral to int value equivalent let map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; let total = 0; for (let i = 0; i < s.length; i++) { let curR = s[i]; let nextR = s[i + 1]; let cur = map[curR]; let next = map[nextR]; if (next) { if (cur >= next) { total += cur; } else { total += next - cur; i++; } } else { total += cur; } return total; } }; console.log(romanToInt("III"), 3); var romanToInt2 = function(s) { const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; let total = 0; for (let i = 0; i < s.length; i++) { let curR = s[i]; let nextR = s[i + 1]; let cur = map[curR]; let next = map[nextR]; if (next) { if (cur >= next) { total += cur; } else { total += next - cur; i++; } } else { total += cur; } } return total; }; console.log(romanToInt2("III"), 3);Acabo de verificar su código, y todo se trata de la declaración de devolución.
La primera función romanToInt devuelve el resultado en el bucle for solo en la primera iteración, mientras que la segunda función, romanToInt2 , el retorno está fuera del bucle for, lo que significa que se ejecuta el bucle for y luego se devuelve el resultado,
Un pequeño truco, en caso de duda de dos funciones exactamente iguales, use cualquier verificador de diferencias y pegue el código para verificar la diferencia. Es fácil notar la diferencia cuando se visualiza. Acabo de poner sus dos funciones aquí , y fue rápido.