Short Python


  • 0

    Here I use a helper function trans to transform the integer under 1000 into its English format. Then, all I need is to split num into parts by every 4 digits and call trans for each part. Of course we need to add the corresponding suffix in C for each trans we called.

    class Solution(object):
        def numberToWords(self, num):
            """
            :type num: int
            :rtype: str
            """
            A = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", \
                 "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", \
                 "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
            B = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
            C = ["Billion", "Million", "Thousand"]
            def trans(n):
                return [] if not n else [A[n // 100], "Hundred"] + trans(n%100) if n >= 100 \
                       else [A[n]] if n < 20 else [B[(n//10)-2]] + trans(n%10)
                        
            res, N = [], [10**9, 10**6, 1000, 1]
            for i in range(4):
                digit, num = divmod(num, N[i])
                if digit: res += trans(digit) + C[i:i+1]
            return " ".join(res) or "Zero"
    

Log in to reply
 

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