688 - 单词表示数字

2017.10.26

三位三位的读,然后再加thousand million billion等单位。

再读每一个三位的时候,后两位需要特殊处理。

此外就是空格的增加需要格外注意一些,这主要是针对几个相连的0出现的情况。

public class Solution {
    /*
     * @param : the number
     * @return: the number in words
     */
	public String convertWords(int number) {
	        // Write your code here
		String num = Integer.toString(number);
		String res = new String();
		if(num.length() <= 3){
			res = read(num);
			return res;
		}
		int count = 0;
		while(num.length() >= 0){
			
			//先读三位
			String tmp = new String();
			if(num.length() >= 3){
				tmp = read(num.substring(num.length()-3, num.length()));
			}
			else{
				tmp = read(num);
			}
			
			// 当count > 0 的时候需要加单位。
			if(count > 0 && !tmp.equals("")){
				tmp = tmp + " ";
				switch(count){
				case 1: 
					tmp = tmp + "thousand";
					break;
				case 2:
					tmp = tmp + "million";
					break;
				case 3:
					tmp = tmp + "billion";
					break;
				default: tmp = tmp;
				}
			}
			//计算加个什么单位
			
			
			count ++;
			if(!res.equals("") && !tmp.equals("")){
				res = " " + res;
			}
			res = tmp + res;
			if(num.length() >= 3){
				num = num.substring(0,num.length()-3);
			}
			else{
				break;
			}
		}
		return res;
	}

	public String read(String s) {
        // Write your code here
		String[] read1 = {"","one","two","three","four","five",
				"six","seven","eight","nine","ten",
				"eleven","twelve","thirteen","fourteen","fifteen",
				"sixteen","seventeen","eighteen","nineteen"};
		String[] read2 = {"","ten","twenty","thirty","forty",
				"fifty","sixty","seventy","eighty","ninety"};
		String res = new String();
		int l = s.length();
		if(l <= 0 ){
			return res;
		}
		if(s.equals("0")){
			return "zero";
		}
		//处理只有一位的情况
		if(l == 1){
			return read1[Integer.valueOf(s)];
		}
		//处理两位的情况     
		     // 1.小于19的时候,需要两位一起读。
		
		if(Integer.valueOf(s.substring(l-2,l)) <= 19){
			res = read1[Integer.valueOf(s.substring(l-2,l))];
		}
		else{
			// 2.大于19的时候,就可以先读十位在读各位了
			String tmp1 = read1[Integer.valueOf(s.substring(l-1,l))];
			String tmp2 = read2[Integer.valueOf(s.substring(l-2,l-1))];
			if(!tmp1.equals("") && !tmp2.equals("")){
				res = tmp2 + " " + tmp1;
			}
			else if(!tmp1.equals("")){
				res = tmp1;
			}
			else{
				res = tmp2;
			}
		}
		if(l == 2){
			return res;
		}
		String tmp3 = read1[Integer.valueOf(s.substring(l-3,l-2))];
		if(tmp3.equals("")){
			return res;
		}
		else if(res.equals("")){
			res = tmp3 + " hundred";
		}
		else{
			res = tmp3 + " hundred " + res;
		}
		return res;
	}
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值