題目
原文:
Given an integer between 0 and 999,999, print an English phrase that describes the integer (eg, “One Thousand, Two Hundred and Thirty Four”).
譯文:
給一個0到999,999的整型,打印一個英文描述的整型(如:“One Thousand, Two Hundred and Thirty Four”)
解答
首先將一位數、十幾、幾十、百千的英文存儲進數組,然後在對1000以上的數和1000以下的進行不同的分析,代碼如下:
import java.lang.StringBuilder; class Q19_6{ public static void main(String[] args){ System.out.println(integerEnglish(94750)); } public static String integerEnglish(int num){ StringBuilder sb=new StringBuilder(); int len=1; while(Math.pow((double)10,(double)len)3&&len%2==0){ len++; } do{ //number greater than 999 if(len>3){ tmp=(num/(int)Math.pow((double)10,(double)len-2)); // If tmp is 2 digit number and not a multiple of 10 if(tmp/10==1&&tmp%10!=0){ sb.append(numstr11[tmp%10]); }else{ sb.append(numstr10[tmp/10]); sb.append(numstr1[tmp%10]); } if(tmp>0){ sb.append(numstr100[len/2]); } num=num%(int)(Math.pow((double)10,(double)len-2)); len=len-2; }else{ // Number is less than 1000 tmp=num/100; if(tmp!=0){ sb.append(numstr1[tmp]); sb.append(numstr100[len/2]); } tmp=num%100; if(tmp/10==1&&tmp%10!=0){ sb.append(numstr11[tmp%10]); }else{ sb.append(numstr10[tmp/10]); sb.append(numstr1[tmp%10]); } len=0; } }while(len>0); } return sb.toString(); } }
---EOF---