This commit is contained in:
parent
501328409d
commit
c91899827b
1 changed files with 33 additions and 0 deletions
33
hard/integer_to_english_words.py
Normal file
33
hard/integer_to_english_words.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
# 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)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue