Search code examples
javascriptintegerroman-numerals

Roman to Integer in JS why it only convert the first character


I try to solve the Leedcode question 13 and the question is Given a roman numeral, convert it to an integer.(Input is guaranteed to be within the range from 1 to 3999.) This is my code below, I wonder why it only converts the first character in the roman numeral to integer?

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'));


Solution

  • Because

    return result;
    

    ends the loop after one iteration. Move it down one line. And if you would do proper formatting, you wouldn't make such mistakes at all ;)

    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'));