273. Integer to English Words

来源:互联网 发布:国研网由哪些数据库 编辑:程序博客网 时间:2024/05/21 06:47

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"12345 -> "Twelve Thousand Three Hundred Forty Five"1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"


三位数字一组,从十亿、百万、千三个单位。

每个单位前的数字最多只有三位,都是由这三位的表示加上例如“Billion"等单位,所以三位数字的表示法可以单独集成一个函数。

每个单词之间都有空格,加着挺麻烦,最后干脆扫一遍去重复的空格。

String[] basewords={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen", "Fifteen","Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"};String[] carrytenwords={"",""," Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"};public String numberToWords(int num){if(num==0)return "Zero";int[] carrys=new int[4];int cnt=0;StringBuilder sb=new StringBuilder();while(num>0){carrys[cnt++]=num%1000;num/=1000;}if(carrys[3]>0){sb.append(getbaseexpress(carrys[3]));sb.append(" Billion ");}if(carrys[2]>0){sb.append(getbaseexpress(carrys[2]));sb.append(" Million ");}if(carrys[1]>0){sb.append(getbaseexpress(carrys[1]));sb.append(" Thousand ");}if(carrys[0]>0)sb.append(getbaseexpress(carrys[0]));char[] carr=new char[sb.length()];int count=0;char prec='-';if(sb.charAt(0)==' ')sb.deleteCharAt(0);if(sb.charAt(sb.length()-1)==' ')sb.deleteCharAt(sb.length()-1);for(int i=0;i<sb.length();i++){char c=sb.charAt(i);if(c==' '){if(c!=prec)carr[count++]=c;}else {carr[count++]=c;}prec=c;}return new String(carr,0,count);}public String getbaseexpress(int num){int carryhunder=0;StringBuilder sb=new StringBuilder();if(num>=100)carryhunder=num/100;num%=100;if(carryhunder>0){sb.append(basewords[carryhunder]);sb.append(" Hundred");}if(num>=90){sb.append(carrytenwords[9]);num-=90;}if(num>=80){sb.append(carrytenwords[8]);num-=80;}if(num>=70){sb.append(carrytenwords[7]);num-=70;}if(num>=60){sb.append(carrytenwords[6]);num-=60;}if(num>=50){sb.append(carrytenwords[5]);num-=50;}if(num>=40){sb.append(carrytenwords[4]);num-=40;}if(num>=30){sb.append(carrytenwords[3]);num-=30;}if(num>=20){sb.append(carrytenwords[2]);num-=20;}sb.append(" ");if(num>0)sb.append(basewords[num]);return sb.toString();}


0 0
原创粉丝点击