演算法題:阿拉伯數字轉化為中文讀法

alicelmx發表於2019-03-13

給出一個五位阿拉伯數字,請寫出它的中文讀法,如:
12345 —> 一萬兩千三百四十五
10000 —> 一萬

這個是貓眼面試官去年問我的一道題目,今天終於把坑填上了,開心~
重點在於0的處理,還有繁雜的字元、字串、整數之間的轉化,那些方法要記牢哦~

package algorithm;
import java.util.*;
public class Solution {
	static char[] numArr = {'零','一','二','三','四','五','六','七','八','九'};
	static String[] unitArr = {"","十","百","千","萬"};
	public static String numToChinese(int num) {
        char[] newNum = String.valueOf(num).toCharArray();
        int len = newNum.length;
        StringBuilder res = new StringBuilder();
        for(int i=0;i<len;i++) {
        	int temp = Integer.parseInt(String.valueOf(newNum[i]));
        	boolean zeroFlag = temp==0 ? true : false;
        	if(zeroFlag) {
        		while(i<len-1 && newNum[i+1]=='0')
        			i++;
        		if(i!=len-1) {
        			res.append(numArr[0]);
        		}
        	}else {
	        	res.append(numArr[temp]);
	        	res.append(unitArr[len-i-1]);
        	}
        }
        return res.toString();
    }
	
	public static void main(String[] args) {
		System.out.print(numToChinese(12345));
		System.out.print("\n");
		System.out.print(numToChinese(10000));
		System.out.print("\n");
		System.out.print(numToChinese(10001));
		System.out.print("\n");
		System.out.print(numToChinese(10100));
		System.out.print("\n");
		System.out.print(numToChinese(10101));
		System.out.print("\n");
		System.out.print(numToChinese(20890));
	}
}

相關文章