Java extensible without trim


  • 0
    K

    import java.util.*;

    public class Solution {

    private static final Map<Integer, String> groups = new LinkedHashMap<>();
    static {
        groups.put(1000000000, "Billion");
        groups.put(1000000, "Million");
        groups.put(1000, "Thousand");
    }
    
    private static final String[] numbers = new String[] {"", "One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", 
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    
    
    private static final String[] teens = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
    public String numberToWords(int num) {
        if (num == 0) return "Zero";
        return print(num, new ArrayList<>()).stream().collect(Collectors.joining(" "));
    }
    
    private List<String> print(int num, List<String> result) {
        for(int g : groups.keySet()) {
            if (num >= g) {
                printGroup(num/g, result);
                result.add(groups.get(g));
                num = num%g;
            }
        }
        return printGroup(num, result);
    }
    
    private List<String> printGroup(int num, List<String> result) {
        if (num >= 100) {
          printGroup(num/100, result);
          result.add("Hundred");
          printGroup(num % 100, result);
        } else if (num >= 20) {
          result.add(teens[num/10]);
          printGroup(num%10, result);
        } else {
          if (num > 0) result.add(numbers[num]);    
        }
        return result;
    }
    

    }


Log in to reply
 

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