688

来源:互联网 发布:飞豆打印软件 编辑:程序博客网 时间:2024/05/17 01:28

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 hereString 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 hereString[] 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;}};


原创粉丝点击