Share my 4ms Java code


  • 0
    M
    public class Solution {
        public String numberToWords(int num) {
            if (num == 0) return "Zero";
            StringBuilder ans = new StringBuilder();
            if (num >= 1000000000) {
                ans.append(parse3Digits(num / 1000000000)).append(" Billion ");
                num %= 1000000000;
            }
            if (num >= 1000000) {
                ans.append(parse3Digits(num / 1000000)).append(" Million ");
                num %= 1000000;
            }
            if (num >= 1000) {
                ans.append(parse3Digits(num / 1000)).append(" Thousand ");
                num %= 1000;
            }
            if (num > 0) ans.append(parse3Digits(num));
            return ans.toString().trim();
        }
        
        private String parse3Digits(int num) {
            String[] below20 = new String[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", 
                "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
            };
            String[] above20 = new String[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
            StringBuilder ans = new StringBuilder();
            if (num >= 100) {
                ans.append(below20[num / 100]).append(" Hundred");
                num %= 100;
                if (num == 0) return ans.toString();
            }
            if (num < 20) {
                ans.append(ans.length() == 0 ? "" : " ").append(below20[num]);
            } else {
                ans.append(ans.length() == 0 ? "" : " ").append(above20[num / 10 - 2]);
                if (num % 10 != 0) ans.append(" ").append(below20[num % 10]);
            }
            return ans.toString();
        }
    }

Log in to reply
 

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