Monday, October 5, 2015

[19.6] Number to English Words

1. Example

Prepend  initialize string as " One" with space ahead.
1.static final level2= {""," Thousand"," Million"," Billion"} 
while( num != 0)
 if ( num % 1000 != 0) {
s = covert(num%1000) + level2[level] + s; 
 }
level++;
num/=1000;
2.
static final level0 = {"", " One"," Two"," Three"," Four"," Five"," Six"," Seven"," Eight"," Nine"," Ten"," Eleven"," Twelve"," Thirteen"," Fourteen"," Fifteen"," Sixteen"," Seventeen"," Eighteen"," Nineteen"} 
 static final level1 = {" Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"}



if ( num > 99 ) { 
 res = leve0[num/100] + " Hundred"; 
 } 


 num%= 100;


if ( num < 20 )
          res = res + level0[num]; 
 else
          res = res + level1[num/10 -2] + level0[num%10];


1,234               => "One Thousand, Two Hundred and Thirty Four"
1,000,999        => "One Million Nine Hundred Ninety Nine"
2,147,483,647 => "Two Billion 147 Million 483 Thousand 647"

// NOTE :1 000 999
if ( num % divisor != 0) { 
      s = covert(num%divisor) + level2[level] + s; 
}

2. Implementation


public static String numToString(int num)
{





       static final level0 = {"", " One"," Two"," Three"," Four"," Five"," Six"," Seven"," Eight"," Nine"," Ten"," Eleven"," Twelve"," Thirteen"," Fourteen"," Fifteen"," Sixteen"," Seventeen"," Eighteen"," Nineteen"}
       static final level1 = {" Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"}
       //static final level2= {"Thousand ","Million ","Billion "}
       // NOTE: loop every time, so we need to set up first unit as ""
       static final level2= {""," Thousand"," Million"," Billion"}






      // validate the input
      if (num == 0)
            return "Zero";






      int divisor = 1000;
      //int val = num % divisor;
      //String s = convert(val);
      String res = "";
      int level = 0;
      //while (num / divisor > 0)
      while( num != 0)
      {
           // NOTE :1 000 999
           if (  num % divisor != 0)
           {
                res = covert(num%divisor) + level2[level] + res;
           }
           num/= divisor;     
      } 




       return res.trim();



}

private String convert(int num)
{




       String res="";
       if ( num > 99 )
       {
            res = leve0[num/100] + " Hundred";
       }



       num%= 100;



       
       if ( num < 20 )
            res = res + level0[num];
       else 
            res = res + level1[num/10 -2] + level0[num%10];

 


       return res;




}
3. Simialr ones

No comments:

Post a Comment