Python 6 Lines Pure Imitation Solution


  • 0

    Just split the integer into groups of 3-digits size, and digest each sub-group seperately.

    class Solution(object):
        def numberToWords(self, num):
            answer, unitidx, unit, toptwty, tophrd, Hrd = '', 0, ['', 'Thousand ', 'Million ', 'Billion '], ['', 'One ', 'Two ', 'Three ', 'Four ', 'Five ', 'Six ', 'Seven ', 'Eight ', 'Nine ', 'Ten ', 'Eleven ', 'Twelve ', 'Thirteen ', 'Fourteen ', 'Fifteen ', 'Sixteen ', 'Seventeen ', 'Eighteen ', 'Nineteen '], ['Twenty ', 'Thirty ', 'Forty ', 'Fifty ', 'Sixty ', 'Seventy ', 'Eighty ', 'Ninety '], ['', 'Hundred ']
            while num:
                h, t, d = (num / 100) % 10, (num / 10) % 10, num % 10
                tmpans = (toptwty[h] + Hrd[1] if h else Hrd[0]) + (toptwty[t*10 + d] if t*10 + d < 20 else tophrd[t - 2] + toptwty[d]) + unit[unitidx]  
                answer, unitidx, num = tmpans + answer if h + t + d != 0 else answer, unitidx + 1, num / 1000
            return answer[:-1] if answer else 'Zero'
    

Log in to reply
 

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