Simple, Pythonic solution


  • 0
    M
    class Solution(object):
        TO19 = "Zero One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen".split()
        TENS = "- - Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split()
        ORDERS = {1e2: "Hundred", 1e3: "Thousand", 1e6: "Million", 1e9: "Billion"}
        
        def numberToWords(self, num):
            return " ".join(self.words(num)) or self.TO19[0]
            
        def words(self, num):
            if num == 0:
                return []
    
            if num < 20:
                return [self.TO19[num]]
    
            if num < 100:
                group = num // 10
                remainder = num % 10
                return [self.TENS[group]] + self.words(remainder)
    
            order = self.find_biggest_order(num)
            group = num // order
            remainder = num % order
            return self.words(group) + [self.ORDERS[order]] + self.words(remainder)
    
        def find_biggest_order(self, num):
            return int(max(order for order in self.ORDERS.keys() if num >= order))
    

Log in to reply
 

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