Re: [閒聊] 每日leetcode

作者: DJYOMIYAHINA (通通打死)   2024-08-07 22:02:07
點點點
其實還蠻好玩的題目==
最後WA了一個1000000
不小心輸出one million thousand
姆咪
def numberToWords(self, num: int) -> str:
a = ["","One ","Two ","Three ","Four ","Five ","Six ","Seven ","Eight
","Nine ","Ten ",
"Eleven ","Twelve ","Thirteen ","Fourteen ","Fifteen ","Sixteen
","Seventeen ","Eighteen ","Nineteen ","Twenty "]
b = ["","","Twenty ","Thirty ","Forty ","Fifty ","Sixty ","Seventy
","Eighty ","Ninety "]
c = ["","Thousand ","Million ","Billion ","Trillion "]
def smaller_than_thousand(n):
if n >= 1000:
print("gg")
return ""
# for < 1000
d = [100,10]
ans = ""
idx = 0
while n>0:
num_cur = n % d[idx]
n = n//d[idx]
if idx == 1:
ans = a[num_cur] + "Hundred " + ans
idx += 1
continue
if num_cur <= 20:
ans = a[num_cur] + ans
idx += 1
continue
else:
tmp = ""
tmp += b[(num_cur//10)]
num_cur = num_cur%10
tmp += a[num_cur]
ans = tmp + ans
idx += 1
continue
return ans
ans = ""
idx = 0
while num>0:
num_cur = num%1000
if num_cur != 0:
ans = smaller_than_thousand(num_cur) + c[idx] + ans
num = num//1000
idx += 1
return "Zero" if ans == "" else ans[:-1]
作者: Smallsh (Smallsh)   2023-08-07 22:02:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com