273. Integer to English Words
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example, 123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Solution:
TO19 = [
'Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',
'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
]
TENS = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
THOUSANDS = ['Thousand', 'Million', 'Billion']
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num < 0:
return 'Negative {}'.format(self.numberToWords(-num))
if num < 20:
return TO19[num]
if num < 100:
tens = TENS[num / 10 - 2]
if num % 10:
return '{} {}'.format(tens, self.numberToWords(num % 10))
return tens
if num < 1000:
hundreds = '{} Hundred'.format(TO19[num / 100])
if num % 100:
return '{} {}'.format(hundreds, self.numberToWords(num % 100))
return hundreds
words = [self.numberToWords(num % 1000)] if num % 1000 else []
for unit in THOUSANDS:
num /= 1000
if num % 1000:
words.append(unit)
words.append(self.numberToWords(num % 1000))
return ' '.join(reversed(words))