阿拉伯数字转中文

猫眼面试题
在这里插入图片描述
错误:
1.String[]数组固定,后面res.add错误,用arraylist或者vector可变数组
2.没有考虑零的个数
1001应该是一千零一,代码输出一千零百零十一
1000应该是一千,代码输出一千零百零十零
正确的代码,如下:

public class NumtoHanzi {
	public static String convertHanzi(String a) {
		String [] uniform = {"零","十","百","千"};
		String [] hanzi = {"零","一","二","三","四","五","六","七","八","九"};
		if(a == null)
			return null;
		int len = a.length();
		int index = len - 1;
		if(a == "10")
			return "十";
		int[] digit = new int[a.length()];
		int i = 0;
		String res = " ";
		while(index >= 0) {
			int num = Integer.parseInt(String.valueOf(a.charAt(index)));
			digit[i] = num;
			index--;
			i++;
		}
		for(int j = len - 1; j >= 0; j--) {
			if(digit[j] != 0) {
				res += hanzi[digit[j]];
				if(j != 0) {
					res += uniform[j];
				}
			}else {
				while(j >=0 && digit[j] == 0) {
					j--;
				}
				if(j == -1)
					break;//全部是零
				//连零被阻断
				res += uniform[0];
				j++;//循环本身还要j--;
			}
			
			
		}
		return res;
	}
	public static void main(String[] args) {
		System.out.println(convertHanzi("1011"));
	}

}

思路:
首先倒序存数,1234存为4321。
然后对于4321,下标3对应的数1,加上uniform对应的下标3的连接词千,当下标为0,不加连接词。
对于零的处理,一直连零到最后,则没有零,如1000或者1100.
连零中间被阻断,则加上“零”,如1001,1011

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值