将数字转换为汉字

迅雷笔试题:

请实现一个方法将一亿以内的数字变成汉语数字


主要有两个要点:

1. 以“万”为分割点,“万”以上的字符处理和“万”以下的字符处理逻辑一致

2. 如果有连续的“零”,那么要合并成一个“零”


public class MyTest {

	public static void main(String[] args) {
		
		Random random = new Random(System.currentTimeMillis());
		
		int i = 1500003;//random.nextInt(100000000);
		
		System.out.println("Befor convert is i = " + i);
		
		System.out.println(convertInt2Chinese(i));
	}
	
	private static String convertInt2Chinese(int num) {
		
		StringBuffer stringBuffer = new StringBuffer();
		
		if (num / 10000 != 0) {
			convertIntBelowWan2Chinese(num / 10000, stringBuffer);
			
			if (stringBuffer.length() != 0) {
				stringBuffer.append("万");
			}
			
			convertIntBelowWan2Chinese(num % 10000, stringBuffer);
		} else {
			convertIntBelowWan2Chinese(num, stringBuffer);
		}
		
		return stringBuffer.toString();
	}
	
	private static String convertIntBelowWan2Chinese(int num, StringBuffer stringBuffer) {
		
		int[] unitArray = {1000, 100, 10, 1};
		String chineseDigitArray = "零壹贰叁肆伍陆柒捌玖";
		String chineseUnitArray = "仟佰拾";
		
		for (int i = 0; i < unitArray.length && num != 0; i++) {
			int quotient = num / unitArray[i];
			
			if (quotient == 0) {
				if (stringBuffer.length() != 0) {
					if (stringBuffer.charAt(stringBuffer.length() - 1) != '零') {
						stringBuffer.append(chineseDigitArray.charAt(quotient));
					}
				}
			} else {
				stringBuffer.append(chineseDigitArray.charAt(quotient));
				if (i < chineseUnitArray.length()) {					
					stringBuffer.append(chineseUnitArray.charAt(i));
				}
			}
			
			num = num % unitArray[i];
		}
				
		return stringBuffer.toString();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值