# These only need to be defined once. # We use lists instead of dictionaries, because it's more efficient (hashing a key still takes cycles). TRANS = [ 'Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', ] TENS = [ '', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', ] def partToArray(array, number, unit): """ Accumulates words corresponding to number in array, with a unit word (if any). """ if number: # hundreds, remainder = divmod(number, 100) hundreds, remainder = number // 100, number % 100 # tens, units = divmod(remainder, 10) tens, units = remainder // 10, remainder % 10 if hundreds: array.append(TRANS[hundreds]) array.append('Hundred') # Note: We could be using proper English... # if remainder: # array.append('And') if remainder >= 21: array.append(TENS[tens]) else: units = remainder if units: # Note: We could be using proper English and use hyphens. array.append(TRANS[units]) if unit: array.append(unit) class Solution(object): def numberToWords(self, number): """ :type num: int :rtype: str """ if number == 0: return 'Zero' array = [] # if number < 0: # array.append('Minus') # number = abs(number) # divmod sounds better, but profiling shows it's more expensive due to function call. # billions, remainder = divmod(number, 1000000000) # millions, remainder = divmod(remainder, 1000000) # thousands, units = divmod(remainder, 1000) billions, remainder = number // 1000000000, number % 1000000000 millions, remainder = remainder // 1000000, remainder % 1000000 thousands, units = remainder // 1000, remainder % 1000 partToArray(array, billions, 'Billion') partToArray(array, millions, 'Million') partToArray(array, thousands, 'Thousand') partToArray(array, units, None) return ' '.join(array)