Iterative solution using Stack no trim()


  • 0
    F

    1 Group every 3 digits and push to stack
    2 pop groups from stack with weight = "Billion", "Million", or "Thousand"
    3 Within each 3 digits group with weight = "hundred", "tens" and "single"

    The less than 20 map is awesome !!!

    private final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
    public String numberToWords(int num) {
        Stack<int[]> threeDigitStack = new Stack<>();
    
        int i = 0;
        int[] threeDigit = new int[3];
        String result = "";
        if (num ==  0)
            return "Zero";
    
        if (num < 0) {
            result = "Nagetive ";
            num = -num;
        }
    
        while(num > 0) {
            int digit = num % 10;
            num = num / 10;
            threeDigit[i] = digit;
            i++;
            if(i == 3) {
                threeDigitStack.push(threeDigit.clone());
                i = 0;
                Arrays.fill(threeDigit,0);
            }
        }
    
        if(i != 0 && (threeDigit[0] != 0 || threeDigit[1] != 0 || threeDigit[2] != 0) )
            threeDigitStack.push(threeDigit.clone());
    
        boolean firstLoop = true;
    
        while(!threeDigitStack.isEmpty()) {
            String weight = "";
            if(threeDigitStack.size() == 4)      weight = " Billion";
            else if(threeDigitStack.size() == 3) weight = " Million";
            else if(threeDigitStack.size() == 2) weight = " Thousand";
    
            threeDigit = threeDigitStack.pop();
    
            int lessThan20 = threeDigit[1] * 10 + threeDigit[0];
            int total = threeDigit[2] * 10 + lessThan20;
    
            if(total != 0 && !firstLoop)
                result += " ";
    
            if(threeDigit[2] != 0) {
                result += LESS_THAN_20[threeDigit[2]] + " " + "Hundred";
                if(lessThan20 != 0)
                    result += " ";
            }
    
            if(lessThan20 != 0) {
                if (lessThan20 < 20)
                    result += LESS_THAN_20[lessThan20];
                else {
                    result += TENS[threeDigit[1]];
                    if(threeDigit[0] != 0)
                        result += " " + LESS_THAN_20[threeDigit[0]];
                }
            }
    
            result += weight;
            firstLoop = false;
        }
    
        return result.substring(0,result.length());
    }

Log in to reply
 

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