Each input file contains one test case, which gives an integer with no more than 9 digits.
For each test case, print in a line the Chinese way of reading the number. The characters are separated by a space and there must be no extra space at the end of the line.
-123456789
Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu
package com.jingmin.advanced; import java.util.Scanner; /** * @author : wangjm * @date : 2020/1/17 01:33 * @discription : https://www.nowcoder.com/pat/1/problem/4312 */ public class Advanced1002 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(new ChineseNumber(n)); scanner.close(); } } class ChineseNumber { /** * 对应的值 */ private int value; /** * 对应的中文 */ private String chinese; /** * 非0标志 */ boolean nonZero = false; /** * 上一位为0,标志 */ boolean lastBitZero = false; /** * 中文拼音 0-9 */ private static String[] CHINESE_NUM = new String[]{"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"}; /** * 十进制位基:千,百,十,个 */ private static String[] CHINESE_BASE = new String[]{" Qian ", " Bai ", " Shi ", " "}; public ChineseNumber(int value) { this.value = value; produceChinese(); } private void produceChinese() { StringBuilder sb = new StringBuilder(); int n = this.value; //判断正负 if (n < 0) { sb.append("Fu "); n = -n; } else if (n == 0) { this.chinese = "ling"; return; } int bufferLength = sb.length(); //获取亿级以上部分(int 最大20+亿) int[] bits = new int[]{0, 0, n / 1000000000, n / 100000000 % 10}; //输出中文到StringBuilder中 print4Bit(sb, bits); //亿级以上不全为0 if (bufferLength != sb.length()) { sb.append("Yi "); bufferLength = sb.length(); } //获取万到千万部分 bits = get4Bit(n % 100000000 / 10000); //输出中文到StringBuilder中 print4Bit(sb, bits); //万到千万部分不全为0 if (bufferLength != sb.length()) { sb.append("Wan "); bufferLength = sb.length(); } //获取个位至千位 bits = get4Bit(n % 10000); //输出中文到StringBuilder中 print4Bit(sb, bits); //更新该实例的中文字段 this.chinese = sb.toString().trim(); } /** * 4位数按10进制位转存到数组 */ private static int[] get4Bit(int num) { int ge = num % 10; int shi = num / 10 % 10; int bai = num / 100 % 10; int qian = num / 1000; return new int[]{qian, bai, shi, ge}; } /** * 输出bits, 其0,1,2,3位分别是千,百,十,个位 */ private void print4Bit(StringBuilder sb, int[] bits) { int bufferLength = sb.length(); //bits 0,1,2,3位分别是千,百,十,个位 for (int i = 0; i < 4; i++) { if (bits[i] != 0) { //处理数字中间的0:当前位不为0,上一位为0,且前面有不为0的位 if (lastBitZero && nonZero) { sb.append(CHINESE_NUM[0]).append(" "); } //以"一十"打头的数字,只输出"十" // if (i == 2 && bits[i] == 1 && !nonZero) { // sb.append(CHINESE_BASE[i]); // } else { sb.append(CHINESE_NUM[bits[i]]).append(CHINESE_BASE[i]); // } nonZero = true; } lastBitZero = bits[i] == 0 ? true : false; } //处理0:如果这四位都是0,下一位非0的话,应该输出0 this.lastBitZero = bufferLength == sb.length() ? true : false; } @Override public String toString() { return this.chinese; } }