用Java写段代码实现:输入一个百亿以内的正整数,把它转换为人民币金额大写表示。
时间: 2024-01-24 07:19:07 浏览: 154
下面是Java的代码实现:
```java
import java.util.Scanner;
public class NumberToRMB {
private static final String[] CN_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] CN_UNITS = {"", "拾", "佰", "仟"};
private static final String[] CN_SECTION_UNITS = {"", "万", "亿"};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long number = scanner.nextLong();
String rmb = convertNumberToRMB(number);
System.out.println(rmb);
}
private static String convertNumberToRMB(long number) {
StringBuilder sb = new StringBuilder();
if (number == 0) {
sb.append(CN_NUMBERS[0]);
return sb.toString();
}
int unitIndex = 0;
while (number > 0) {
int section = (int) (number % 10000);
if (section != 0) {
StringBuilder sectionSb = new StringBuilder();
int units = 0;
while (section > 0) {
int digit = section % 10;
if (digit != 0) {
sectionSb.insert(0, CN_NUMBERS[digit] + CN_UNITS[units]);
} else {
if (sectionSb.length() > 0 && !sectionSb.substring(0, 1).equals(CN_NUMBERS[0])) {
sectionSb.insert(0, CN_NUMBERS[0]);
}
}
units++;
section /= 10;
}
sb.insert(0, sectionSb.toString() + CN_SECTION_UNITS[unitIndex]);
}
unitIndex++;
number /= 10000;
}
if (sb.substring(0, 1).equals(CN_NUMBERS[0])) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
```
这个程序可以将一个百亿以内的正整数转换为人民币金额的大写表示。例如,输入`123456789`,输出`壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整`。
阅读全文