封面画师: あずーる
twitter:@azure_0608_sub
题目链接:https://leetcode-cn.com/problems/integer-to-english-words/
主要是准确度的问题,英语中三位换千、百万、十亿,在数学上不难,就是烦。
答案仅适用于int32,因为题目写明:0 <= num <= 231 - 1
var Enumber = [...]string{"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight","Nine","Ten","Eleven","Twelve","Thirteen", "Fourteen", "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}
var Mnumber = [10]string{"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}
var BMT = [4]string{"Billion", "Million", "Thousand", ""}
func numberToWords(num int) string {
if num == 0 {
return Enumber[0] //直接返回Zero
}
sb := strings.Builder{}
for i, j := 1000000000, 0; i > 0; i, j = i/1000, j+1 {
if num < i {
continue
}
sb.WriteString(numToStr(num/i) + BMT[j] + " ")
num %= i
}
return strings.TrimSpace(sb.String())
}
func numToStr(x int) (ans string) {
if x >= 100 {
ans += Enumber[x/100] + " Hundred "
x %= 100
}
if x >= 20 {
ans += Mnumber[x/10] + " "
x %= 10
}
if x != 0 {
ans += Enumber[x] + " "
}
return
}
在十位数控制的时候Mnumber[0]和 Mnumber[1]留""方便后面操作,不加入Hundred主要是为了后面判断位数再加。
Comments NOTHING