面试时被问到这个问题,遂查看相关博客,自己也作了相应的实现:
package num2rmb;
public class Num2Rmb3 {
/**
* 处理0,1,2.。9的中文读法的
*/
private String[] hanArr = {"零" , "壹" , "贰" , "叁" , "肆" , "伍" , "陆" , "柒" , "捌" , "玖"};
/**
* 10进制的读法
*/
private String[] unitArr = {"十" , "百" , "千"};
public static void main(String[] args) {
Num2Rmb3 nr = new Num2Rmb3();
nr.readNumString("1052433768");
// nr.readNumString("5000");
// System.out.println(Math.ceil(3.5)); //4.0
}
public void readNumString(String numstr)
{
StringBuilder sb = new StringBuilder();
int len = numstr.length();
int count = 0;
while (len > 0) //依次取出最后,以4位字符为标准取子串
{
int i = (len - 4) >= 0 ? (len - 4) : 0;
String temp = numstr.substring(i, len);
System.out.println(temp);
String res = processTemp(temp, count); // 对这四个字符进行处理
sb.insert(0, res); //往前将求得的字符串插入sb中
len -= 4;
count++; // 记录这个子串中能组成多少个 4个字符的串
}
System.out.println(sb);
}
public String processTemp(String temp, int count)
{
String res = "";
int len1 = temp.length();
// 0042
// 200
for (int i = 0; i < len1; i++)
{
//将每个字符转成数字
int num = temp.charAt(i) - 48;
if (num == 0) //如果是0
{
if (i == (len1 - 1)) //到了子串的最后一个字符
{
continue;
}
//如果下一个是数字字符不是0
if (temp.charAt(i + 1) != '0')
{
res += hanArr[num];
}
else {
continue;
}
}
else if( i == (len1 - 1) ) { //不是0,最后一个字符
res += hanArr[num];
}
else //
{
res += hanArr[num] + unitArr[len1 - i - 2];
}
}
if (count == 1)
{
res += "万";
}
else if (count == 2)
{
res += "亿";
}
return res;
}
}