LC 0273 [H] Integer to English Words - ALawliet/algorithms GitHub Wiki

  • a map of the possible ints and a map of the possible word
  • remember to map the ones, teens, tens, hundred, thousand, million, billion
  • try to divide (/) the biggest number we can with recursion
  • consider >= 100 because "one hundred"/"one thousand" vs. "eighty"/"ninety"
  • then include the remainder (%) with recursion
  • test with number over 100 to cover cases e.g. 152 => "one hundred fifty two"
div, mod = divmod(num, i)
r(div)+' ' + word+' ' + r(mod)
^ if i >= 100
if i >= 100: # numbers over 100 have more words
    res += self.helper(quotient) + ' ' + word + ' ' + self.helper(remainder)
else:
    res += word + ' ' + self.helper(remainder)
if i >= 100: # numbers over 100 have more words
    res += f'{self.helper(quotient)} {word} {self.helper(remainder)}'
else:
    res += f'{word} {self.helper(remainder)}'

ints = [1000000000, 1000000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
words = ["Billion", "Million", "Thousand", "Hundred", "Ninety", "Eighty", "Seventy", "Sixty", "Fifty", "Forty", "Thirty", "Twenty", "Nineteen", "Eighteen", "Seventeen", "Sixteen", "Fifteen", "Fourteen", "Thirteen", "Twelve", "Eleven", "Ten", "Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One"];

class Solution:
    def numberToWords(self, num: int) -> str:
        if num == 0: return 'Zero'
        return self.helper(num)
    
    def helper(self, num):
        res = ''

        for i, word in zip(ints, words): # check possible dividers from largest to smallest
            if num >= i:
                quotient, remainder = divmod(num, i)

                if i >= 100: # numbers over 100 have more words
                    res += self.helper(quotient) + ' '
                    
                res += word + ' ' + self.helper(remainder)

                break # just use the first largest i that num divides into

        return res.strip()