大家一起来讨论一道java面试题
题目如下:
金额转换,阿拉伯数字的金额转换成中国传统的形式如:
(¥1011)-> (一千零一拾一元整)输出。
我写的程序如下:
public class MoneyTransfer {
static String transfer(char c)
{
String ch = null;
switch(c){
case '1 ':
ch= "一 ";
break;
case '2 ':
ch= "二 ";
break;
case '3 ':
ch= "三 ";
break;
case '4 ':
ch= "四 ";
break;
case '5 ':
ch= "五 ";
break;
case '6 ':
ch= "六 ";
break;
case '7 ':
ch= "七 ";
break;
case '8 ':
ch= "八 ";
break;
case '9 ':
ch= "九 ";
break;
}
return ch;
}
public static void main(String[] args)
{
String[] str={ "千亿 ", "百亿 ", "十亿 ", "亿 ", "千万 ", "百万 ", "十 万 ", "万 ", "千 ", "百 ", "拾 ", "元 "};
char[] num = new char[12];
try {
BufferedReader in = new BufferedReader(new InputStreamReader (System.in));
String number = in.readLine();
char[] Cnumber = number.toCharArray();
for(int i=Cnumber.length-1,j=num.length-1;i> =0;i--,j--)
{
num[j]=Cnumber[i];
}
} catch (
IOException e) {
e.printStackTrace();
}
int m=0;
while(num[m]== 0)
m++;
for(int n=m;n <num.length;n++)
if(num[n] != '0 ')
System.out.print(transfer(num[n])+ " "+str[n]);
else
System.out.print( "零 ");
}
}
但总是觉得写的太复杂,特别是用树组str保存单位那里觉得不是很好,大家有没有什么好的办法,一起来讨论学习啊
------解决方案--------------------小弟贴一个,望指教
public class test{
int number[];
String bignum[] = { "零 ", "一 ", "二 ", "三 ", "四 ", "五 ", "六 ", "七 ", "八 ", "久 "};
String sign1[] = { " ", "十 ", "百 ", "千 "};
String sign2[] = { "圆 ", "万 ", "亿 ", "兆 "};
test(String s){
s = s.replaceFirst( "^0+ ", " ");
if(s.length()> sign2.length*4)
System.exit(0);
number = new int[s.length()];
for(int i=0;i <s.length();i++)
number[s.length()-1-i] = Integer.parseInt(i==s.length()-1?s.substring(i):s.substring(i,i+1));
run();
}
void run(){
String s= " ";
for(int i=number.length-1;i> =0;i--){
s+=bignum[number[i]];
s+=i%4==0?sign2[i/4]:number[i]> 0?sign1[i%4]: " ";
}
while(s.indexOf( "零零 ")!=-1)
s=s.replaceFirst( "零零 ", "零 ");
for(int i=0;i <sign1.length;i++)
while(s.indexOf( "零 "+sign2[i])!=-1)
s=s.replaceFirst( "零 "+sign2[i],sign2[i]);
for(int i=sign2.length-1;i> 0;i--)
while(s.indexOf(sign2[i]+sign2[i-1])!=-1)
s=s.replaceFirst(sign2[i]+sign2[i-1],sign2[i]);
System.out.println(s);