题解 | #人民币转换#
人民币转换
http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
public class Test {
private static String[] chineseCharacter = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static String[] unit = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟","万"};
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextLine()){
StringBuilder result = new StringBuilder("人民币");
String src = in.nextLine();
String zn = null;
String pn = null;
if(src.contains(".")){
String[] numStr = src.split("\\.");
zn = numStr[0];
pn = numStr[1];
dealBeforePlot(zn, result);
String s = result.toString();
if(!s.equals("人民币")){
result.append("元");
}
dealAfterPlot(pn, result);
}else{
zn = src;
dealBeforePlot(zn, result);
String s = result.toString();
if(!s.equals("人民币")){
result.append("元整");
}
// dealAfterPlot(pn, result);
}
System.out.println(result);
}
}
public static void dealBeforePlot(String intStr,StringBuilder result){
if(intStr.equals("0")) return;
if(intStr.charAt(0) == '0') return;
// int helpIndex = intStr.length() - 1; //用来将数字和 要映射的数组下标对应
boolean isZero = false; //用来记录上一个是否为0
for(int i = 0; i < intStr.length(); i++){
int helpIndex = intStr.length() - 1 - i; //将第i个数字和 单位数组的下标对应
int curNum = Integer.parseInt(String.valueOf(intStr.charAt(i))); //对第i个 数字进行映射
switch(curNum){//用来加 中文值
case 0://当前的数等于0
if(!isZero){//第一次为0,将isZero标记为true
if( unit[helpIndex] != null && (helpIndex % 4 == 0)) {
result.append(unit[helpIndex]);
continue;
/**
* 如果没加continue会报如下的错误
*
* 用例输入
* 1024.56
* 10012.02
* 100110.00
* 30105000.00
* 预期输出
* 人民币壹仟零贰拾肆元伍角陆分
* 人民币壹万零拾贰元贰分
* 人民币拾万零壹佰拾元整
* 人民币叁仟零拾万伍仟元整
*
* 实际输出:
* 人民币壹仟零贰拾肆元伍角陆分
* 人民币壹万零拾贰元贰分
* 人民币拾万零壹佰拾元整
* 人民币叁仟零拾万零伍仟元整 ---------- 伍仟元前 多了个零
*/
}
result.append(chineseCharacter[0]);
isZero = true;
}
break;
case 1://按照题意,当单位含有 "拾" 的时候,只填写单位
if(!"拾".equals(unit[helpIndex])){
result.append(chineseCharacter[1]);
}
isZero = false;
break;
default:
result.append(chineseCharacter[curNum]);
isZero = false;
break;
}
//加对应的单位
if(unit[helpIndex] != null && !isZero){//当不是个位数且不是 0的地方就添加单位
result.append(unit[helpIndex]);
}
}
if(result.charAt(result.length() - 1) == '零'){//去掉个位数为 零的情况
result = result.deleteCharAt(result.length() - 1);
}
if(result.charAt(0) == '零'){
result = result.deleteCharAt(0);
}
}
//处理小数部分
public static void dealAfterPlot(String plotStr, StringBuilder result){
if(plotStr.equals(null) || "00".equals(plotStr)){
result.append("整");
}
if(plotStr.charAt(0) != '0'){
result.append(chineseCharacter[plotStr.charAt(0) - '0']);
result.append("角");
}
if(plotStr.charAt(1) != '0'){
result.append(chineseCharacter[plotStr.charAt(1) - '0']);
result.append("分");
}
}
}

快手公司福利 1308人发布