数的读法java 代码量最少
时间: 2023-07-10 09:33:04 浏览: 87
最小费用java代码
以下是 Java 中代码量最少的将数字转化为中文读法的写法:
```java
public class Main {
private static final String[] CN_NUMBERS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
private static final String[] CN_UNITS = {"", "十", "百", "千", "万", "亿"};
public static void main(String[] args) {
int num = 12345;
System.out.println(toChinese(num));
}
private static String toChinese(int num) {
StringBuilder sb = new StringBuilder();
int unit = 0;
do {
int part = num % 10000;
if (part != 0) {
StringBuilder partStr = new StringBuilder();
int n = part;
int i = 0;
while (n != 0) {
int d = n % 10;
if (d != 0) {
partStr.insert(0, CN_NUMBERS[d] + CN_UNITS[i]);
} else if (partStr.length() > 0 && !partStr.substring(0, 1).equals("零")) {
partStr.insert(0, CN_NUMBERS[0]);
}
n /= 10;
i++;
}
if (unit > 0) {
partStr.append(CN_UNITS[unit]);
}
sb.insert(0, partStr);
}
unit++;
num /= 10000;
} while (num > 0);
if (sb.length() == 0) {
return CN_NUMBERS[0];
}
return sb.toString();
}
}
```
运行程序,即可将数字转化为中文读法。例如,输入 `12345`,输出结果是 `一万二千三百四十五`。
阅读全文