Created
October 4, 2018 20:34
-
-
Save yokolet/f02a3fcc56651d834379f13b08292dc6 to your computer and use it in GitHub Desktop.
Integer to English Words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Description: | |
Convert a non-negative integer to its english words representation. Given input is | |
guaranteed to be less than 2**31 - 1. | |
Examples: | |
Input: 123 | |
Output: "One Hundred Twenty Three" | |
Input: 12345 | |
Output: "Twelve Thousand Three Hundred Forty Five" | |
Input: 1234567891 | |
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand | |
Eight Hundred Ninety One" | |
""" | |
def numberToWords(num): | |
""" | |
:type num: int | |
:rtype: str | |
""" | |
base_dict = { | |
0: ('', 'Ten'), | |
1: ('One', 'Eleven'), | |
2: ('Two', 'Twelve', 'Twenty'), | |
3: ('Three', 'Thirteen', 'Thirty'), | |
4: ('Four', 'Fourteen', 'Forty'), | |
5: ('Five', 'Fifteen', 'Fifty'), | |
6: ('Six', 'Sixteen', 'Sixty'), | |
7: ('Seven', 'Seventeen', 'Seventy'), | |
8: ('Eight', 'Eighteen', 'Eighty'), | |
9: ('Nine', 'Nineteen', 'Ninety') | |
} | |
orders = [ | |
'', ' Thousand', ' Million', ' Billion', ' Trillion' | |
] | |
def conv_2digits(v): | |
tens, ones = divmod(v, 10) | |
if tens == 0: | |
return base_dict[ones][0] | |
elif tens == 1: | |
return base_dict[ones][1] | |
else: | |
if base_dict[ones][0]: | |
return base_dict[tens][2] + ' ' + base_dict[ones][0] | |
else: | |
return base_dict[tens][2] | |
def conv_3digits(v): | |
# 3 digits | |
hundreds, tens = divmod(v, 100) | |
if hundreds == 0: | |
return conv_2digits(tens) | |
word = base_dict[hundreds][0] + ' Hundred' | |
if tens == 0: | |
return word | |
else: | |
return word + ' ' + conv_2digits(tens) | |
if num == 0: | |
return 'Zero' | |
cur = num | |
word = '' | |
order = 0 | |
while True: | |
if cur == 0: | |
break | |
cur, m = divmod(cur, 1000) | |
v = conv_3digits(m) | |
if v: | |
v += orders[order] | |
if word: | |
word = v + ' ' + word | |
else: | |
word = v | |
order += 1 | |
return word |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment