My easy to understand Java solution


  • 0
    Y
    public class Solution {
        static List<String> bigs = Arrays.asList("", "Thousand", "Million", "Billion");
        static String hundred = "Hundred";
        static List<String> tens = Arrays.asList("", "One", "Two", "Three", "Four", "Five", "Six",
                "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
                "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                "Nineteen");
        static List<String> bigTens = Arrays.asList("", "", "Twenty", "Thirty", "Forty", "Fifty",
                "Sixty", "Seventy", "Eighty", "Ninety");
        public static String numberToWords(int num) {
            if (num == 0) {
                return "Zero";
            }
            boolean isNeg = false;
            if (num < 0) {
                isNeg = true;
                num = -num;
            }
            List<Integer> nums = new ArrayList<>();
            while (num != 0) {
                nums.add(num % 1000);
                num /= 1000;
            }
    
            StringBuilder sb = new StringBuilder();
            for (int i = nums.size() - 1; i >= 0; i--) {
                if (nums.get(i) != 0) {
                    sb.append(convertHundred(nums.get(i)));
                    sb.append(" ");
                    sb.append(bigs.get(i));
                    sb.append(" ");
                }
            }
    
            return (isNeg ? "Negative " : "") + sb.toString().trim();
        }
    
        static String convertHundred(int num) {
            StringBuilder sb = new StringBuilder();
            if (num / 100 > 0) {
                sb.append(tens.get(num / 100));
                sb.append(" ");
                sb.append(hundred);
                sb.append(" ");
                num %= 100;
            }
    
            if (num >= 20) {
                sb.append(bigTens.get(num / 10));
                sb.append(" ");
                num %= 10;
            }
    
            sb.append(tens.get(num));
    
            return sb.toString().trim();
        }
    }
    

Log in to reply
 

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