Integer to Numeral (Javascript)


  • 0
    S
    const decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
    const romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
    
    const addNumeralsToString = (symbol, noOfTimes) => {
      let result = '';
      for(let i = 0; i< noOfTimes; i++){
        result = `${result}${symbol}`;
      }
      return result;
    };
    
    module.exports = (num) => {
    
      let result = '';
      let remainder = num;
    
      decimals.forEach((num, idx) => {
        const numberOfTimes = Math.floor(remainder/num);
        remainder = remainder%num;
        result = `${result}${addNumeralsToString(romans[idx], numberOfTimes)}`;
      });
    
      return result;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.