Skip to content

Instantly share code, notes, and snippets.

@wtfcarlos
Created May 27, 2020 14:45
Show Gist options
  • Select an option

  • Save wtfcarlos/bb15c5b449073ea12a06df4719c6d9a3 to your computer and use it in GitHub Desktop.

Select an option

Save wtfcarlos/bb15c5b449073ea12a06df4719c6d9a3 to your computer and use it in GitHub Desktop.
PPOP.PY
nums_1_19_1 = [
None,
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen",
]
nums_20_90_10 = [
None,
None,
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety",
]
powers_of_10 = [
(1e9, "Billion"),
(1e6, "Million"),
(1e3, "Thousand"),
(1e2, "Hundred"),
]
def concat_str(s1, s2):
return f"{s1} {s2} "
class Solution:
def numberToWords(self, num):
if num == 0:
return "Zero"
return ' '.join(self.numberToWordsHelper(num).split())
def numberToWordsHelper(self, num: int) -> str:
# 1234567891
if num == 0:
return ""
if num < 20:
return nums_1_19_1[num]
if num < 100:
quant = int(num // 10)
remainder = int(num % 10)
return concat_str(nums_20_90_10[quant], self.numberToWordsHelper(remainder))
remainder = num
result = ""
for power, name in powers_of_10:
quant = int(remainder // power)
remainder = int(remainder % power)
if quant == 0:
continue
result += concat_str(
self.numberToWordsHelper(quant),
name
)
if remainder > 0:
result += self.numberToWordsHelper(remainder)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment