Answers for "Roman to interger"

0

Roman to interger

var romanToInt = function (s) {
  const converter = value => {
    switch (value) {
      case 'I':
        return 1
      case 'IV':
        return 4
      case 'V':
        return 5
      case 'IX':
        return 9
      case 'X':
        return 10
      case 'XL':
        return 40
      case 'L':
        return 50
      case 'XC':
        return 90
      case 'C':
        return 100
      case 'CD':
        return 400
      case 'D':
        return 500
      case 'CM':
        return 900
      case 'M':
        return 1000
      default:
        break
    }
  }
  let sum = 0
  const arrRoman = s.split('')

  const checkArr = [...arrRoman]

  for (let index in arrRoman) {
    if (+index + 1 < checkArr.length) {
      if (
        (arrRoman[index] === 'I' && arrRoman[+index + 1] === 'V') ||
        (arrRoman[index] === 'I' && arrRoman[+index + 1] === 'X') ||
        (arrRoman[index] === 'X' && arrRoman[+index + 1] === 'L') ||
        (arrRoman[index] === 'X' && arrRoman[+index + 1] === 'C') ||
        (arrRoman[index] === 'C' && arrRoman[+index + 1] === 'D') ||
        (arrRoman[index] === 'C' && arrRoman[+index + 1] === 'M')
      ) {
        arrRoman.splice(index, 2, arrRoman[index] + arrRoman[+index + 1])
      }
    }
  }

  for (let romNum of arrRoman) {
    sum += converter(romNum)
  }
  return sum
}

var romanToInt = function(str) {
    const code = {
        'I': 1, 
        'V': 5, 
        'X': 10, 
        'L': 50, 
        'C': 100, 
        'D': 500, 
        'M': 1000
    }
    
    let total = 0;
    
    for (let i = 0; i < str.length; i++) {
        let current = code[str[i]];
        let next = code[str[i + 1]];
        
        if (current < next) {
            total -= current;
        } else {
            total += current;
        }
    }
    return total;
};
Posted by: Guest on February-10-2022

Browse Popular Code Answers by Language