Too long by myself!!!struggling with the space between words,who can help?


  • 0
    public class Solution {
    public String numberToWords(int num) {
         if(num==0)
            return "Zero";
        String  aArray[]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
        String  bArray[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        String  cArray[]={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
        String  str=new String();
        int tmp,a,b,c,cnt=0;
        do{ 
            ++cnt;
            if(cnt==2){
                if(str.length()==0)
                    str="Thousand"+str;
                    else
                        str="Thousand "+str;}
            else if(cnt==3){
               if(str.length()==0)
                    str="Million"+str;
                    else
                        str="Million "+str;}
            else if(cnt==4){
               if(str.length()==0)
                    str="Billion"+str;
                    else
                        str="Billion "+str;}
            tmp=num%1000;
            a=tmp/100;
            b=tmp%100/10;
            c=tmp%100%10;
            if(b==1){
                if(cnt==1)
                    str=bArray[c]+str;
                    else
                        str=bArray[c]+" "+str;
                if(a!=0)
                        str=aArray[a]+" Hundred "+str;
                num/=1000;
               continue;
            }
            else{
                if(str.length()==0)
                    str=aArray[c]+str;
                    else
                        str=aArray[c]+" "+str;
                if(b==0||c==0)
                    str=cArray[b]+str;
                    else
                        str=cArray[b]+" "+str;
                if(a!=0&&"".equals(str))
                    str=aArray[a]+" Hundred"+str;
                    else if(a!=0&&!("".equals(str)))
                        str=aArray[a]+" Hundred "+str;
                    
            }
            num/=1000;
        }while(num>0);
         return str;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.