Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-08-07 21:07:47
273. Integer to English Words
把數字換成英文表示法
思路:
分成 num<20、20<=num<100、100<=num<1000、1000<=num<1000000、1000000<=num<1000000000
這幾個區段
然後就照著寫就好
滿無聊的題目
golang code :
func OneTeen(num int) string {
ones := [20]string{"",
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten
",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen
", "Eighteen", "Nineteen",
}
return ones[num%20]
}
func Ten(num int) string {
if num < 20 {
return OneTeen(num)
}
_Ten := [8]string{"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "
Eighty", "Ninety"}
var digit string
if num%10 != 0 {
digit = " " + OneTeen(num%10)
}
return _Ten[num/10-2] + digit
}
func Hundred(num int) string {
if num < 100 {
return Ten(num)
}
var digit string
if num%100 != 0 {
digit = " " + Ten(num%100)
}
return Ten(num/100) + " Hundred" + digit
}
func Thousand(num int) string {
if num < 1000 {
return Hundred(num)
}
var digit string
if num%1000 != 0 {
digit = " " + Hundred(num%1000)
}
return Hundred(num/1000) + " Thousand" + digit
}
func Million(num int) string {
if num < 1000_000 {
return Thousand(num)
}
var digit string
if num%1000_000 != 0 {
digit = " " + Thousand(num%1000_000)
}
return Hundred(num/1000_000) + " Million" + digit
}
func Billion(num int) string {
if num < 1000_000_000 {
return Million(num)
}
var digit string
if num%1000_000_000 != 0 {
digit = " " + Million(num%1000_000_000)
}
return Hundred(num/1000_000_000) + " Billion" + digit
}
func numberToWords(num int) string {
if num == 0 {
return "Zero"
}
if num < 100 {
return Ten(num)
}
if num < 1000 {
return Hundred(num)
}
if num < 1000_000 {
return Thousand(num)
}
if num < 1000_000_000 {
return Million(num)
}
if num < 2_147_483_648 {
return Billion(num)
}
return ""
}
作者: oin1104 (是oin的說)   2024-08-07 21:09:00
我好崇拜你
作者: CCapocalypse (CCinfinity)   2024-08-07 21:10:00
這題真的好煩

Links booklink

Contact Us: admin [ a t ] ucptt.com