日期:2014-05-19  浏览次数:20829 次

关于Java的算法(经典面试题)
在控制台输入数字(0、1、2、3、4、5、6、7、8、9、10……)
在控制台输出中文大写(零、壹、贰、叁、肆、伍、陆、柒、捌、玖、拾……)
eg:  
  101 --》壹佰零壹
  100010 --》拾万零壹拾

仰望高手【】

------解决方案--------------------
import java.util.Scanner;

public class ChNumber {

public String getInt(){
Scanner sc = new Scanner(System.in);
String str = null;
System.out.println("请输入一个整数:");
while(true){
str = sc.nextLine();
if(str.matches("\\d+")){
break;
}else{
System.out.println("你输入数的格式不正确,请重新输入一个整数:");
}
}
return String.valueOf(Long.parseLong(str));
}

public int get(char c){
String s = String.valueOf(c);
return Integer.parseInt(s);
}

public String change(String str){
char c[] = str.toCharArray();
String s = "";
int count = 0;
int temp;
String upper[] ={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
for(int i=c.length-1;i>=0;i--){
temp = get(c[i]);
count++;
if(count==2||(count%4)==2){
s = upper[temp]+"拾"+s;
}else if(count==3||(count%4)==3){
s = upper[temp]+"佰"+s;
}else if(count==4||(count%4)==0){
s = upper[temp]+"仟"+s;
}else if(count==5){
s = upper[temp]+"万"+s;
}else if(count==9){
s = upper[temp]+"亿"+s;
}else if(count==13){
s = upper[temp]+"兆"+s;
}else{
s = upper[temp]+s;
}
}
return s;
}

public static void main(String[] args) {
ChNumber cn = new ChNumber();
String s = cn.change(cn.getInt());
s = s.replaceAll("零[拾佰仟]", "零");
s = s.replaceAll("零{4}万", "零");
s = s.replaceAll("零{4}亿", "零");
s = s.replaceAll("零{4}兆", "零");
s = s.replaceAll("零{2,}", "零");
s = s.replaceAll("零万", "万");
s = s.replaceAll("零亿", "亿");
s = s.replaceAll("零兆", "兆");
s = s.replaceAll("零{2,}", "零");
if(s.endsWith("零")){
s = s.substring(0, s.length()-1);
}
System.out.println(s);
}

}

新手,乱写的,仅供参考
------解决方案--------------------
借鉴前人,写了个思路比较清晰的:
Java code

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Convert_Number_Chinese {
    public static final String[] Str_Number={"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
    public static final String[] Str_Location={ "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
  
    
    public static String getSign(String tempString) {//拿到符号
        return tempString.indexOf("-")!=-1?"负":"";
    }
   
    
    public static String getInteger(String tempStr) {//拿到整数部分
        String Str_Integer="";//去掉两端空格
        tempStr=tempStr.trim();
        if(tempStr.matches("^0+[.].+")) {
            tempStr=tempStr.replaceFirst("^0+", "0");//e.g:  000.123改为0.123
            return "零";
        }
        if(tempStr.matches("^0+")) {
            return "零";//e.g:  00000
        }
        tempStr=tempStr.replaceFirst("^0+",