Recursive python, may not be concise but somewhat easy to understand


  • 0
    S
        def numberToWords(self, num):
            """
            :type num: int
            :rtype: str
            """
            """
            billion  = 1,000,000,000
            million  = 1,000,000
            thousand = 1,000
            hundred  = 100
            """
            units = [
                "Zero",     #0
                "One",      #1
                "Two",      #2
                "Three",    #3
                "Four",     #4
                "Five",     #5
                "Six",      #6
                "Seven",    #7
                "Eight",    #8
                "Nine",     #9
                "Ten",      #10
                "Eleven",   #11
                "Twelve",   #12
                "Thirteen", #13
                "Fourteen", #14
                "Fifteen",  #15
                "Sixteen",  #16
                "Seventeen",    #17
                "Eighteen", #18
                "Nineteen"] #19
            tens  = [
                "",         #nothing begins with 0 for two digit number
                "",         #numbers that begins with 1 for two digit number taken care in units array
                "Twenty",   #2
                "Thirty",   #3
                "Forty",    #4
                "Fifty",    #5
                "Sixty",    #6
                "Seventy",  #7
                "Eighty",   #8
                "Ninety"]   #9
            
            def _util(num):
                res = ""
    
                names  = [ ' Billion ', ' Million ', ' Thousand ', ' Hundred ' ]
                ranges = [ 10**9, 10**6, 10**3, 10**2]
                for name,_range in zip(names,ranges):
                    if num >= _range:
                        if num % _range:
                            res = _util(num//_range) + name + _util(num%_range)
                        else:
                            res = _util(num//_range) + name
                        return res.strip()
                    
                # num is below hundred!
                if 0 <= num <= 19:
                    res = units[num]
                else:
                    if num % 10:
                        res = tens[num//10] + ' ' + units[num%10]
                    else:
                        res = tens[num//10]
                return res.strip()
            
            return _util(num)

Log in to reply
 

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