题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
能发现每四位的单位或者说数阶是相同的:
// 10^0 个位
// 10^1 拾
// 10^2 佰
// 10^3 仟
// 10^4 万
// 10^5 拾万
// 10^6 佰万
// 10^7 仟万
// 10^8 亿
// 10^9 拾亿
// 10^10 佰亿
// 10^11 仟亿
public class Main {
static String[] mapLev = new String[] {"", "拾", "佰", "仟", "万"};
static String[] map = new String[] {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] d = br.readLine().trim().toCharArray();
int n = d.length;
String res = "";
// 四位四位读整数部分
// 15 1121.15
int ln = n-3;
res = read4(Math.max(0, ln-4), ln, d);
if (ln-4 > 0)
res = read4(Math.max(0, ln-8), ln-4, d) + "万" + res;
if (ln - 8 > 0)
res = read4(Math.max(0, ln-12), ln-8, d) + res + "亿";
res = "人民币" + res;
// 处理小数部分
if (d[ln] == '.') {
// 小数全为 0
if (d[ln+1] == '0' && d[ln+2] == '0') {
if (n == 4) { // 特例: 0.00
System.out.println("零元整");
} else {
System.out.println(res + "元整");
}
// 小数不全为 0
} else {
// 没有整数部分
if (n == 4 && d[ln-1] == '0') {
System.out.println(res + map[d[ln+1]-'0'] + "角" + map[d[ln+2]-'0'] + "分");
// 有整数部分
} else {
if (d[ln-1] == '0') res += "零";
// 角为 0 分不为 0
if (d[ln+1] == '0') {
System.out.println(res + "元" + map[d[ln+2]-'0'] + "分");
// 分为 0 角不为 0
} else if (d[ln+2] == '0') {
System.out.println(res + "元" + map[d[ln+1]-'0'] + "角" );
// 角分全不为 0
} else {
System.out.println(res + "元" + map[d[ln+1]-'0'] + "角" + map[d[ln+2]-'0'] + "分" );
}
}
}
}
}
public static String read4(int start, int end, char[] d) {
if (start >= end) return "";
String res = "";
for (int i = start; i < end; ++i) {
int k = i;
while (d[k] == '0' && k < end) k++;
if (k - i >= 1) {
// xx0.xx 整数最后一位为 0 不添加 零
if (k < d.length-3) {
res += "零";
}
i = k - 1;
continue;
}
// 1x 读作 拾x,而不是 壹x
if (d[i] == '1' && mapLev[end-i-1].equals("拾")) {
res += "拾";
} else {
res += map[d[i] - '0'] + mapLev[end - i-1];
}
}
return res;
}
}

CVTE公司福利 672人发布