题解 | #阿拉伯数字转中文#
阿拉伯数字转中文
https://www.nowcoder.com/practice/6eec992558164276a51d86d71678b300
package main
import (
"strings"
"strconv"
)
func num2cn(n int) string {
if n == 0 {
return "零"
}
negative := false
if n < 0 {
negative = true
n = -n
}
ans := ""
// 亿
if n >= 100000000 {
x := n / 100000000
ans = ans + thousandNum2Cn(x) + "亿"
}
if len(ans) != 0 && n%100000000 != 0 {
bytes := []byte(strconv.Itoa(n))
if i := len(bytes) - 8; i >= 0 && i < len(bytes)-4 {
if bytes[i] == '0' {
ans += "零"
}
}
}
n %= 100000000
// 万
if n >= 10000 {
x := n / 10000
ans = ans + thousandNum2Cn(x) + "万"
}
if len(ans) != 0 && n%10000 != 0 {
bytes := []byte(strconv.Itoa(n))
if i := len(bytes) - 4; i >= 0 && i < len(bytes) {
if bytes[i] == '0' {
ans += "零"
}
}
}
n %= 10000
thousand := thousandNum2Cn(n)
if thousand != "零" {
ans = ans + thousand
}
if negative {
ans = "负" + ans
}
return ans
}
func thousandNum2Cn(n int) string {
if n == 0 {
return "零"
}
ans := ""
numStr := []string{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}
units := []string{"", "十", "百", "千"}
unit := 0
for n > 0 {
x := n % 10
if x == 0 {
if !strings.HasPrefix(ans, numStr[0]) { // 中间多个零的略去
ans = numStr[0] + ans
}
} else {
ans = numStr[x] + units[unit] + ans
}
n /= 10
unit++
}
if strings.HasPrefix(ans, "一十") {
ans = strings.Replace(ans, "一十", "十", 1)
}
if strings.HasSuffix(ans, "零") {
ans = strings.TrimSuffix(ans, "零")
}
return ans
}
TODO
