Easy understanding 6ms Java solution


  • 0

    public class Solution {
    public String numberToWords(int num) {

        // Error checking
        if(num==0) return "Zero";
        
        
        StringBuilder sb = new StringBuilder("");
        if(num>=1000000000){ // One Billion
            int forBillion = num/1000000000;
            String forBillionString = getWords(forBillion);
            sb.append(forBillionString+"Billion ");
            num = num-forBillion*1000000000;
        }
        if(num>=1000000){
            int forMillion = num/1000000;
            String forMillionString = getWords(forMillion);
            sb.append(forMillionString+"Million ");
            num = num-forMillion*1000000;
        }
        if(num>=1000){
            int forThousand = num/1000;
            String forThousandString = getWords(forThousand);
            sb.append(forThousandString+"Thousand ");
            num = num-forThousand*1000;
        }
        if(num>0){
            String forDigitString = getWords(num);
            sb.append(forDigitString);
        }
        
    
        if(sb.charAt(sb.length()-1)==' ') return sb.deleteCharAt(sb.length()-1).toString();
        return sb.toString();
        
        
        
    }
    
    public String getWords(int number){
        
        int[] vals = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,30,40,50,60,70,80,90};
        String[] strs = {"zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        
        StringBuilder sb = new StringBuilder("");
        
        if(number>=100){
            int h = number/100;
            sb.append(strs[h]+" Hundred ");
            number = number-h*100;
        }
        
        
        if(number>=20){
            int ty = number/10;
            sb.append(strs[ty+18]+" ");
            number = number-ty*10;
        }
        
        if(number>10 && number<20){ sb.append(strs[number]+" "); return sb.toString();}
    
        if(number>0){
            sb.append(strs[number]+" ");
        }
        
        return sb.toString();
    }
    

    }


Log in to reply
 

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