My accepted Java solution (248ms)


  • 2
    B
    public class Solution {
        public String numberToWords(int num) {
            if(num == 0){
                return "Zero";
            }
            StringBuffer sb = new StringBuffer();
            
            String chunk = getRepresentation(num / 1000000000);   
            if(chunk.length() != 0){
                sb.append(chunk + " Billion ");
                num = num % 1000000000;
            }
            
            chunk = getRepresentation(num / 1000000);
            if(chunk.length() != 0){
                sb.append(chunk + " Million ");
                num = num % 1000000;
            }
            
            chunk = getRepresentation(num / 1000);
            if(chunk.length() != 0){
                sb.append(chunk + " Thousand ");
                num = num % 1000;
            }
            
            chunk = getRepresentation(num);
            if(chunk.length() != 0){
                sb.append(chunk);
            }
            
            return sb.toString().trim();
        }
        
        public String getRepresentation(int digit){
            String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
            String[] lessThan20 = {"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
            String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
            String res = "";
            if(digit == 0){
                return res;
            }
    
            if(digit >= 100){
                res += ones[digit / 100] + " Hundred ";
                digit = digit % 100;
            }
    
            if(digit < 10){
                res += ones[digit];
                return res.trim();
            }
    
            int temp = digit % 10;
            digit = digit / 10;
            
            if(temp == 0){
                res += tens[digit];
            }else if(digit == 1){
                res += lessThan20[temp];
            }else{
                res += tens[digit] + " " + ones[temp];
            }
    
            return res.trim();
        }
    }

Log in to reply
 

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