华为笔试 数字转中文拼音

题目:输入一个整数数字,输出该数字的中文拼音

比如:54        wushisi

        100      yibai

        6006    liuqianlingliu

        60006    liuwanlingliu

 

解题思路:

首先要把数字的读音和数字对应起来,十位、百位、千位。。。等等的读音对应起来

接下来要考虑到几种情况:

1、各位为零

2、中间有连续几个零

3、当整数大于万以后怎么读

参考代码:

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String line = in.nextLine();
            HashMap<Integer, String> frist = new HashMap<Integer, String>();
            frist.put(1, "shi");
            frist.put(2, "bai");
            frist.put(3, "qian");
            frist.put(4, "wan");
            frist.put(8, "yi");
            HashMap<Integer, String> read = new HashMap<Integer, String>();
            read.put(1, "yi");
            read.put(2, "er");
            read.put(3, "san");
            read.put(4, "si");
            read.put(5, "wu");
            read.put(6, "liu");
            read.put(7, "qi");
            read.put(8, "ba");
            read.put(9, "jiu");
            read.put(0, "ling");

            int num = Integer.parseInt(line);
            StringBuilder sb = new StringBuilder();
            int i = 0;
            int j = 0;

            while (num != 0) {
                j = num % 10;
                if (i != 0 && j != 0) {
                    sb.insert(0, frist.get(i));
                    sb.insert(0, read.get(j));
                } else if (i != 0 && j == 0) {
                    if (sb.toString().length() != 0 && sb.indexOf("ling")!=0){//中间连续几个零
                        sb.insert(0, read.get(0));
                    }
                } else if (i == 0 && j != 0) {
                    sb.insert(0, read.get(j));
                }

                i++;
                if (i > 4) {
                    i = i % 4;//当位数大于万
                }
                num = num / 10;
            }
            String str = sb.toString();
            str = str.replaceAll("null", "");

            System.out.println(str);
        }
    }
}

 

posted @ 2016-09-07 10:21  googlemeoften  阅读(849)  评论(0编辑  收藏  举报