看到的一道美团的面试题,示例:输入1234,输出一千二百三十四,最大到亿
这道题目的复杂点在于对于数字中零的处理,想了半天想不到好的方法,只能分情况讨论,希望各位大神赐教,代码如下:
public static void translate(int n){
String number = n+"";
char[] cs = number.toCharArray();
StringBuilder sb = new StringBuilder();
char[] num = {'零','一','二','三','四','五','六','七','八','九'};
String[] weight = {"","十","百","千"};
for(int i=0;i<cs.length;i++){
if(cs.length-i==9){
sb.append(num[cs[i]-'0']+"").append("亿");
}else if(cs.length-i>=5&&cs.length-i<=8){
if(cs[i]-'0'!=0){
sb.append(num[cs[i]-'0']+"").append(weight[cs.length-i-5]);
}else{
if(cs.length-i==8){
sb.append("零");
}else if(cs.length-i==7){
if(cs[i-1]=='0'||(cs[i+1]=='0'&&cs[i+2]=='0'))
{
}
else {
sb.append("零");
}
}else if(cs.length-i==6){
if(cs[i-1]=='0'||cs[i+1]=='0')
{
}else {
sb.append("零");
}
}
}
if(cs.length-i==5)
sb.append("万");
}else{
if(cs[i]-'0'!=0){
sb.append(num[cs[i]-'0']+"").append(weight[cs.length-i-1]);
}else{
if(cs.length-i==4){
sb.append("零");
}else if(cs.length-i==3){
if(cs[i-1]=='0'||(cs[i+1]=='0'&&cs[i+2]=='0'))
{
}
else {
sb.append("零");
}
}else if(cs.length-i==2){
if(cs[i-1]=='0'||cs[i+1]=='0')
{
}else {
sb.append("零");
}
}
}
}
}
System.out.println(sb.toString());
}
怎么才能很好的解决出现0的问题,并且使代码优化呢?