Easy to Understand JAVA Solution


  • 0
    A
    String[] one = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    String[] elevens = { "", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    String[] tens = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    
    public String numberToWords(int num) {
    	if (num == 0) return "Zero";
    	int b = num / 1000000000;
    	int m = (num % 1000000000) / 1000000;
    	int t = (num / 1000) % 1000;
    	String result = ( b != 0 ? numberToWordsSize3(b) + " Billion " : "" )
    	        	  + ( m != 0 ? numberToWordsSize3(m) + " Million " : "" )
    	        	  + ( t != 0 ? numberToWordsSize3(t) + " Thousand " : "" ) 
    	        	  + numberToWordsSize3(num % 1000);
    	return result.trim();
    }
    
    public String numberToWordsSize3(int num) {
    	int h = num /100;
    	int l = num % 100;
    	String result = (h > 0 ? one[h] + " Hundred " : "")
    				+ (l >= 11 && l <= 19 ? elevens[l % 10]
    				 : (l % 10 == 0 ? tens[l / 10]
    				  : (tens[l / 10] + (l / 10 ==0 ? "" : " " ) + one[l % 10])));							
    	return result.trim();
    }

Log in to reply
 

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