33 lines
1.3 KiB
Python
33 lines
1.3 KiB
Python
# https://leetcode.com/problems/integer-to-english-words
|
|
LOCALE = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
|
|
LOCALE_TEN = ['empty', 'empty', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
|
|
HUNDRED = 'Hundred'
|
|
LOCALE_UNIT = ['Thousand', 'Million', 'Billion', 'Trillion']
|
|
UNIT = 1000
|
|
class Solution:
|
|
def numberToWords(self, num: int) -> str:
|
|
stack = []
|
|
while num >= UNIT:
|
|
stack.append(num % UNIT)
|
|
num //= UNIT
|
|
stack.append(num % UNIT)
|
|
result = []
|
|
def translate(val: int):
|
|
if val == 0:
|
|
result.append(LOCALE[val])
|
|
return
|
|
if val >= 100:
|
|
result.append(LOCALE[val // 100])
|
|
result.append(HUNDRED)
|
|
val %= 100
|
|
if val >= 20:
|
|
result.append(LOCALE_TEN[val // 10])
|
|
val -= (val // 10) * 10
|
|
if val == 0:
|
|
return
|
|
result.append(LOCALE[val])
|
|
while len(stack) > 0:
|
|
translate(stack.pop())
|
|
if len(stack) > 0:
|
|
result.append(LOCALE_UNIT[len(stack) - 1])
|
|
return ' '.join(result)
|