Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-08-08 07:08:27
https://leetcode.com/problems/integer-to-english-words
273. Integer to English Words
Python Code:
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return "Zero"
def one(num):
"""Convert a number less than 20 to words."""
switcher = [
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"
, "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
]
return switcher[num - 1] if num > 0 else ""
def ten(num):
"""Convert a number between 20 and 99 to words."""
switcher = [
"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "
Eighty", "Ninety"
]
return switcher[num // 10 - 2] if num >= 20 else ""
def two(num):
"""Convert a number less than 100 to words."""
if num < 20:
return one(num)
else:
return ten(num) + ("" if num % 10 == 0 else " " + one(num % 10
))
def three(num):
"""Convert a number less than 1000 to words."""
if num == 0:
return ""
elif num < 100:
return two(num)
else:
return one(num // 100) + " Hundred" + ("" if num % 100 == 0
else " " + two(num % 100))
def convert(num):
"""Convert a number to words."""
if num == 0:
return "Zero"
billion = num // 1000000000
million = (num // 1000000) % 1000
thousand = (num // 1000) % 1000
remainder = num % 1000
result = ""
if billion > 0:
result += three(billion) + " Billion"
if million > 0:
result += (" " if result else "") + three(million) + " Million
"
if thousand > 0:
result += (" " if result else "") + three(thousand) + "
Thousand"
if remainder > 0:
result += (" " if result else "") + three(remainder)
return result.strip()
return convert(num)
字太多懶得手打
一開始估狗 "數字 英文 全" 顯示的網站說分成4組 所以就 :(
懶得改了

Links booklink

Contact Us: admin [ a t ] ucptt.com