JS O(n) solution with Maps


  • 0
    Y
    const onesWords = new Map([
      ['1', 'One'],
      ['2', 'Two'],
      ['3', 'Three'],
      ['4', 'Four'],
      ['5', 'Five'],
      ['6', 'Six'],
      ['7', 'Seven'],
      ['8', 'Eight'],
      ['9', 'Nine'],
    ])
    
    const tensWords = new Map([
      ['10', 'Ten'],
      ['11', 'Eleven'],
      ['12', 'Twelve'],
      ['13', 'Thirteen'],
      ['14', 'Fourteen'],
      ['15', 'Fifteen'],
      ['16', 'Sixteen'],
      ['17', 'Seventeen'],
      ['18', 'Eighteen'],
      ['19', 'Nineteen'],
      ['2', 'Twenty'],
      ['3', 'Thirty'],
      ['4', 'Forty'],
      ['5', 'Fifty'],
      ['6', 'Sixty'],
      ['7', 'Seventy'],
      ['8', 'Eighty'],
      ['9', 'Ninety'],
    ])
    
    const placesWords = new Map([
      [6, 'Thousand'],
      [9, 'Million'],
      [12, 'Billion'],
    ])
    
    // returns an array whose entries are triples of the number
    //
    // 12345 -> ['345', '012']
    // 1234567 -> ['567', '234', '001']
    //
    function getHundredUnits(number) {
      const hundreds = []
      const numberString = number.toString()
      const length = numberString.length
      let hundredUnit = ''
      for (let i = length - 1, steps = 0; i > -1; i--, steps++) {
        hundredUnit = numberString.charAt(i) + hundredUnit
        if (i === 0 || ((steps + 1) % 3) === 0) {
          while (hundredUnit.length < 3) {
            hundredUnit = `0${hundredUnit}`
          }
          hundreds.push(hundredUnit)
          hundredUnit = ''
        }
      }
      return hundreds
    }
    
    // https://leetcode.com/problems/integer-to-english-words/
    function numberToWords(number) {
      if (!number) {
        return 'Zero'
      }
      const byHundreds = getHundredUnits(number)
      const words = []
      let places = 0
      for (const hundredsUnit of byHundreds) {
        const [numHundreds, numTens, numOnes] = hundredsUnit
        places += hundredsUnit.length
        let hundredsWord, tensWord, onesWord
        if (numHundreds !== '0') {
          hundredsWord = `${onesWords.get(numHundreds)} Hundred`
        }
        if (numTens === '1') {
          tensWord = tensWords.get(`${numTens}${numOnes}`)
        } else {
          tensWord = tensWords.get(numTens)
          onesWord = onesWords.get(numOnes)
        }
        const placesWord = placesWords.get(places)
        const word = []
        if (hundredsWord) {
          word.push(hundredsWord)
        }
        if (tensWord) {
          word.push(tensWord)
        }
        if (onesWord) {
          word.push(onesWord)
        }
        if (placesWord && (hundredsWord || tensWord || onesWord)) {
          word.push(placesWord)
        }
        if (word.length) {
          words.unshift(word.join(' '))
        }
      }
      return words.join(' ')
    }
    

Log in to reply
 

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