Java clean solution


  • 2
    J
    private String[] digit = new String[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private String[] teen = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] ten = new String[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] thousand = new String[] {"Thousand", "Million", "Billion"};
    
    public String numberToWords(int num) {
    	String ans;
    	if (num == 0)
    		return digit[num];
    	
    	ans = hundredHelper(num%1000);
    	num = num/1000;
    	int i = 0;
    	while (i < 3 && num > 0) {
    		if (num % 1000 > 0)
    			ans = hundredHelper(num%1000) + thousand[i] + " " + ans;
    		num = num/1000;
    		i++;
    	}
    	
    	return ans.trim();
    }
    
    public String hundredHelper(int num) {
    	String nstr = "";
    	if (num >= 100) {
    		nstr = digit[num/100] + " Hundred ";
    	}
    	num = num%100;
    	if (num >= 20) {
    		if (num % 10 != 0)
    			nstr = nstr + ten[num/10 - 2] + " " +  digit[num%10] + " ";
    		else
    			nstr = nstr + ten[num/10 - 2] + " ";
    	} else if (num >= 10) {
    		nstr = nstr + teen[num%10] + " ";
    	} else if (num > 0){
    		nstr = nstr + digit[num] + " ";
    	}
    	return nstr;
    }

Log in to reply
 

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