3ms Java solution beats 97.90%


  • 1
    W

    The code explains itself.

    private String[] units = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private String[] tenToTwenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
    public String numberToWords(int num) {
    	if (num < 0) return "";
    	if (num < 10) return units[num];
    	if (num < 20) return tenToTwenty[num - 10];
    	if (num < 100) return tens[num / 10] + (num % 10 == 0 ? "" : " " + numberToWords(num % 10));
    	if (num < 1000) return numberToWords(num / 100) + " Hundred" + (num % 100 == 0 ? "" : " " + numberToWords(num % 100));
    	if (num < 1000000) return numberToWords(num / 1000) + " Thousand" + (num % 1000 == 0 ? "" : " " + numberToWords(num % 1000));
    	if (num < 1000000000) return numberToWords(num / 1000000) + " Million" + (num % 1000000 == 0 ? "" : " " + numberToWords(num % 1000000));
    	
    	return numberToWords(num / 1000000000) + " Billion" + (num % 1000000000 == 0 ? "" : " " + numberToWords(num % 1000000000));
    }
    

  • 0
    C

    very impressive


Log in to reply
 

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