告诉你什么是优雅的代码(6)------阿拉伯钱数转换为中文形式

本文介绍了一种优雅的算法,用于将长整型数字转换成中文大写形式,例如将1011转换为“一千零一十一”。该算法通过合理划分数字块,并使用字符串缓冲区来提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://www.iteye.com/topic/766812[/url]里谈到
题目: 将正整数的阿拉伯钱数转换为中文形式,如1011→一千零一十一,输出。

作者做得相当啰嗦,也比较低效,正好有缘遇到优雅代码大师区区在下,于是一段优雅代码得以诞生:



public class MoneyTrans {

private static String[] ChinaDigit = {"零","一","二","三","四","五","六","七","八","九"};
private static String[] UNIT = {"","","十","百","千"};
private static String[] BIGUNIT = {"","万","亿","兆"};
private static long MAX = 10000000000000000L - 1;
private char[] digit;
public String trans(long n) throws Exception{
if(n > MAX){
throw new Exception("数字过大,最多可处理到千兆位");
}
StringBuffer buff = new StringBuffer();
boolean isPrePartZero = false;
digit = String.valueOf(n).toCharArray();
int length = digit.length;
int pos = (length - 1)/4;
int headLength = (length - 1)%4 + 1;
// xxxxxxxxxx --> xx|xxxx|xxxx
buff.append(partTrans(0,headLength) + BIGUNIT[pos--]);
for (int i = headLength;i < length ; i = i + 4) {
String part = partTrans(i , i + 4);
if(part.length() == 0){
isPrePartZero = true;
}else{
if(isPrePartZero && !part.startsWith(ChinaDigit[0])){
buff.append(ChinaDigit[0]);
}
buff.append(part + BIGUNIT[pos]) ;
isPrePartZero = false;
}
pos--;
}
return buff.toString();
}

private String partTrans(int start, int end) {
StringBuffer buff = new StringBuffer();
boolean isPreDigitZero = false;
for (int i = start; i < end; i++) {
int cur = digit[i] - '0';
if(cur != 0 ){
if(isPreDigitZero){
buff.append(ChinaDigit[0]);
}
buff.append(ChinaDigit[cur] + UNIT[end - i]);
isPreDigitZero = false;
}
else {
isPreDigitZero = true;
}
}
return buff.toString();
}

public static void main(String[] args) throws Exception {
MoneyTrans transtor = new MoneyTrans();
String money = transtor.trans(9000000000000000L);
System.out.println(money);
}

}




结果:

九千兆
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值