http://www.javaeye.com/topic/766812里谈到
题目: 将正整数的
阿拉伯钱数转换为中
文形式,如1011→一千零一十一,输出。
作者做得相当啰嗦,也比较低效,正好有缘遇到优雅代码大师区区在下,于是一段优雅代码得以诞生:
public class MoneyTrans {
private static String[] ChinaDigit = {"零","一","二","三","四","五","六","七","八","九"};
private static String[] UNIT = {"","","十","百","千"};
private static String[] BIGUNIT = {"","万","亿"};
private char[] digit;
public String trans(int n){
StringBuffer buff = new StringBuffer();
digit = String.valueOf(n).toCharArray();
int length = digit.length;
int pos = (length - 1)/4;
int headLength = (length - 1)%4 + 1;
buff.append(partTrans(0,headLength) + BIGUNIT[pos--]);
for (int i = headLength;i < length ; i = i + 4) {
buff.append(partTrans(i , i + 4) + BIGUNIT[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 == true){
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) {
MoneyTrans transtor = new MoneyTrans();
String money = transtor.trans(23005602);
System.out.println(money);
}
}
结果:
二千三百万五千六百零二
网友 2012/3/17 21:24:02 发表
integer型的,太小了,字符串:1000010167800 错了。