Python solution


  • 0
    A
    class Solution(object):
        def numberToWords(self, num):
            """
            :type num: int
            :rtype: str
            """
            if num==0: return 'Zero'
            
            res = []
            
            to19 = '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()
            
            def trans(digit):
                if digit >= 100:
                    return [to19[digit/100-1]] + ["Hundred"] + trans(digit%100)
                elif digit >= 20: 
                    return [tens[digit/10 -2]] + trans(digit%10)
                elif digit >= 1: 
                    return [to19[digit-1]]
                else: 
                    return []
    
            bmt = ['Billion','Million','Thousand','Unit']
            
            for i, digit in enumerate(bmt):
                digit = num/1000**(3-i)
                if digit>0: res += trans(digit) + [bmt[i]]
                num = num - digit*1000**(3-i)
                
                
            if res[-1]=='Unit':
                return ' '.join(res)[:-5]
            else: return ' '.join(res) 
    

Log in to reply
 

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