golang实现——数字转换中文大写

今天和同事讨论,头条面试的算法题,他说问了一个金额大小写转换的,即1024 转成壹千零贰拾肆圆整,然后自己尝试一下了(不考虑小数,金额数字小数点只能到两位了)
具体思路如下:逐个读取每个数字,然后对应取中文数字,并加上中文单位,最后把一些需要处理的描述,比如零零,换成零,把零万,换成零等。
具体如下:
package mainimport ( "fmt" "strings" )func transfer(num int) string{ chineseMap:=[]string{"圆整","十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"} chineseNum:=[]string{"零", "壹", "贰","叁","肆","伍","陆","柒","捌","玖"} listNum := []int{} for ; num >0; num = num/10{ listNum= append(listNum, num%10) } n :=len(listNum) chinese :="" //注意这里是倒序的 for i:=n-1; i>=0 ; i-- { chinese = fmt.Sprintf("%s%s%s", chinese, chineseNum[listNum[i]], chineseMap[i]) } //注意替换顺序 for { copychinese:=chinese copychinese = strings.Replace(copychinese, "零万", "万", 1) copychinese = strings.Replace(copychinese, "零亿", "亿", 1) copychinese = strings.Replace(copychinese, "零十", "零", 1) copychinese = strings.Replace(copychinese, "零百", "零", 1) copychinese = strings.Replace(copychinese, "零千", "零", 1) copychinese = strings.Replace(copychinese, "零零", "零", 1) copychinese = strings.Replace(copychinese, "零圆", "圆", 1)if copychinese == chinese { break }else { chinese= copychinese } }return chinese }func main() { fmt.Println(1024, transfer(1024)) fmt.Println(1004, transfer(1004)) fmt.Println(101004, transfer(101024)) fmt.Println(1010004, transfer(1010004)) fmt.Println(3000010004, transfer(3000010004)) }

【golang实现——数字转换中文大写】测试一下
1024 壹千零贰十肆圆整 1004 壹千零肆圆整 101004 壹十万壹千零贰十肆圆整 1010004 壹百零壹万零肆圆整 3000000 叁百万圆整 3000010004 叁十亿零壹万零肆圆整

    推荐阅读