算法题:设计函数实现将中文数字转换成int型数字,例如”一百二十三” 转换成123,要求写出测试用例。
package com.test;
import java.util.*;
public class CNCharsToNumber {
public static void main(String[] args) {
System.out.println("Test: " + CNCharsToNumber.CnToNumber("一十亿零五百万八千零二十三"));
}
public static int CnToNumber(String str) {
int result = 0;
HashMap<Character, Integer> nM = new HashMap<Character, Integer>();
nM.put('一', 1);
nM.put('二', 2);
nM.put('三', 3);
nM.put('四', 4);
nM.put('五', 5);
nM.put('六', 6);
nM.put('七', 7);
nM.put('八', 8);
nM.put('九', 9);
HashMap<Character, Integer> bitMap = new HashMap<Character, Integer>();
bitMap.put('十', 10);
bitMap.put('百', 100);
bitMap.put('千', 1000);
bitMap.put('万', 10000);
bitMap.put('亿', 100000000);
System.out.println("Start");
char[] charNum = str.toCharArray();
int n, bit1 = 0, bit2 = 0;
for(int i = 0; i < charNum.length; i++) {
if(nM.containsKey(charNum[i])) {
n = (int)nM.get(charNum[i]);
if(i + 1 < charNum.length && bitMap.containsKey(charNum[i + 1])){
i++;
bit1 = (int)bitMap.get(charNum[i]);
if(i + 1 < charNum.length && bitMap.containsKey(charNum[i + 1])) {
// 进位处理,例如一百万
i++;
bit2 = (int)bitMap.get(charNum[i]);
if(result ==0) {
result = n * bit1 * bit2;
} else {
result = result + n * bit1 * bit2;
}
} else { // 进位处理,例如一百
if(result == 0) {
result = n * bit1;
} else {
result = result + n * bit1;
}
}
} else { // 个位数的处理
result = result + n;
}
} else if(charNum[i] == '零'){
} else {
System.out.println("The input string contain illegal characters: " + charNum[i]);
break;
}
}
return result;
}
}