1305. Integer to English Words
Description:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
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”
Code:
class Solution:
"""
@param num: a non-negative integer
@return: english words representation
"""
def numberToWords(self, num):
# Write your code here
if num == 0:
return "Zero"
word1000 = ["", " Thousand", " Million", " Billion", " Trillion"]
st = '%d'%num
ls = len(st)
unit = math.floor((ls-1)/3)
res = ""
if ls%3 == 2:
res = self.eng(int(st[:2])) + word1000[unit]
st = st[2:]
elif ls%3 == 1:
res = self.eng(int(st[0])) + word1000[unit]
st = st[1:]
elif ls%3 == 0:
res = self.eng(int(st[:3])) + word1000[unit]
st = st[3:]
unit -= 1
while unit >= 0:
tmp = st[:3]
res = res + " " + self.eng(int(tmp[:])) + word1000[unit]
st = st[3:]
unit -= 1
return res
def eng(self, num):
word1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
word10 = ["Ten", "Eleven", "Twelve", "Thirteen", "Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
word20 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
st = '%d'%num
if len(st) == 1:
return word1[num]
if len(st) == 2 and num<20:
return word10[int(st[1])]
if len(st) == 2 and num>=20:
if num%10 == 0:
return word20[int(st[0])]
elif num%10 != 0:
return word20[int(st[0])] + " " + self.eng(int(st[1]))
if len(st) == 3:
return word1[int(st[0])] + " Hundred " + self.eng(int(st[1:]))