Simple Python Solution


  • 0
    class Solution(object):
        def numberToWords(self, num):
            i = 0
            a = ['',' Thousand',' Million',' Billion']
            ans = ''
            while num > 0:
                if num%1000 > 0:
                    ans = self.helper(num%1000) + a[i] + ans
                num /= 1000
                i += 1
            return ans[1:] if ans else 'Zero'
        
        def helper(self, num):
            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']
            s = ''
            if num/100 > 0:
                s += a[num/100] + ' Hundred'
            num %= 100
            if num < 20:
                return s + a[num]
            return s + b[num/10] + a[num%10]

Log in to reply
 

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