今天在网上看到一个笔试题挺有意思,就是将阿拉伯数字转化为中文,在用网银转账的时候见过这个功能,于是自己做了一下,下面是用递归实现的代码。
package info.lwjlaser.practice;
import java.util.Arrays;
/*
* 将阿拉伯数字转化为中文数字(不支持小数点)如:12345转化为一万二千三百四十五。
* @author lwjlaser,lwj.charles
*/
public class Arab2Chinese {
private char cnum[]={'零','一','二','三','四','五','六','七','八','九'};
public void convert(long num){
String numStr=String.valueOf(num);
char [] chars=numStr.toCharArray();
System.out.println(convert(chars));
}
private String convert(char [] chars){
StringBuilder sb = new StringBuilder();
if(chars.length > 8){
char [] beforeYi=Arrays.copyOfRange(chars, 0, chars.length-8);
char [] AfterYi=Arrays.copyOfRange(chars, chars.length-8, chars.length);
sb.append(convert(beforeYi)).append("亿").append(convert(AfterYi));
}
else if(chars.length > 4){
char [] beforeWan=Arrays.copyOfRange(chars, 0,chars.length-4);
char [] afterWan=Arrays.copyOfRange(chars, chars.length-4, chars.length);
sb.append(convert(beforeWan)).append("万").append(convert(afterWan));
}
else{
int length = chars.length;
int val=0;
int zeroCount=0;
for(int i=0;i < length; i++){
val=Integer.parseInt(chars[i]+"");
//处理数字中的零,如:12340,10033,10333,10303,10300,10000
if(0==val){
zeroCount++;
continue;
}
if(zeroCount!=0){
sb.append("零");
zeroCount=0;
}
sb.append(cnum[val]);
switch (length-1-i)
{
case 3:
sb.append("千");
break;
case 2:
sb.append("百");
break;
case 1:
sb.append("十");
break;
}
}
}
return sb.toString();
}
}