Share My 4ms java solution, easy to understand


  • 0
    S

    FYI

    public String numberToWords(int num) {
            //if(num == 0) return "Zero";
            StringBuilder sb = new StringBuilder();
            
            if (num >= 1000000000) { 
                sb.append(helper(num /1000000000) + " Billion");
                num %= 1000000000;
                if(num != 0) {
                    sb.append(" ");
                }else {
                    return sb.toString();
                }
            }
            
            if(num >= 1000000) { 
                sb.append(helper(num / 1000000) + " Million");
                num %= 1000000;
                if(num != 0) {
                    sb.append(" ");
                }else {
                   return sb.toString();
                }
            }
            
            if(num >= 1000) { 
                sb.append(helper(num / 1000) + " Thousand");
                num %= 1000;
                if(num != 0) {
                    sb.append(" ");
                }else {
                    return sb.toString();
                }
            }
            
            if(num > 0) { 
                sb.append(helper(num));
            }
            
            return sb.toString();
        }
        
        private String helper(int n) { 
            //deal with n < 1000
            StringBuilder sb = new StringBuilder();
            String one[] = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine" };
            String ten[] = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
            String eleven[] = {"Ten","Eleven", "Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
      
            if(n >= 100) { 
                sb.append(one[n/100] + " Hundred");
                n %= 100;
                if(n != 0) {
                    sb.append(" ");
                }else { 
                    return sb.toString();
                }
            }
            
            if(n >= 20) { 
                sb.append(ten[n/10]);
                n %= 10;
                if(n != 0) {
                    sb.append(" ");
                }else { 
                    return sb.toString();
                }
            } else if(n >= 10) { 
                sb.append(eleven[n%10]);
            } 
            
            if(10 > n && n > 0){ 
                sb.append(one[n]);
            }
            return sb.toString();
        }

Log in to reply
 

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