My Slow solution. Easy to understand but Slow


  • 0
    G

    public class Solution {

    String[] pron = {"", "Thousand", "Million", "Billion"};
    
    public String numberToWords(int num) {
        if(num == 0){return "Zero";}
        StringBuilder sb = new StringBuilder();
        int count = 0;
        while(num > 0){
            String temp = hudredsToWords(num % 1000);
            if(temp.length() != 0){
                sb.insert(0, temp + " " + pron[count] + " ");
            }
            count++;
            num /= 1000;
        }
        return sb.toString().trim().replaceAll("\\s+", " ");
    }
    
    public String hudredsToWords(int num){
        if(num < 100){return tensToWords(num);}
        return onesToWords(num/100) + " Hundred " + tensToWords(num % 100);
    }
    
    public String tensToWords(int num){
        if(num <= 10){return onesToWords(num);}
        else if(num < 20){
            switch(num){
                case 11: return "Eleven";
                case 12: return "Twelve";
                case 13: return "Thirteen";
                case 15: return "Fifteen";
                case 18: return "Eighteen";
            }
            return onesToWords(num - 10) + "teen";
        }
        else{
            if(num < 30){ return "Twenty " + onesToWords(num - 20);}
            else if(num < 40){ return "Thirty " + onesToWords(num - 30);}
            else if(num < 50){ return "Forty " + onesToWords(num - 40);}
            else if(num < 60){ return "Fifty " + onesToWords(num - 50);}
            else if(80 <= num && num < 90){return "Eighty " + onesToWords(num - 80);}
            else{
                return onesToWords(num / 10) + "ty " + onesToWords(num % 10);
            }
        }
    }
    
    public String onesToWords(int num){
        switch(num){
            case 0: return "";
            case 1: return "One";
            case 2: return "Two";
            case 3: return "Three";
            case 4: return "Four";
            case 5: return "Five";
            case 6: return "Six";
            case 7: return "Seven";
            case 8: return "Eight";
            case 9: return "Nine";
            case 10: return "Ten";
        }
        return "";
    }
    

    }


Log in to reply
 

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