Java solution with TreeMap


  • 0
    M

    Java solution with TreeMap. Pre setup the map with values and corresponding string, and the solve it recursively.

    public class Solution {
        
        private TreeMap<Integer, String> numMap = new TreeMap<>();
    
        public String numberToWords(int num) {
            if (num == 0) {
                return "Zero";
            }
            setup();
            return numberToWordsHelper(num);
        }
        
        private String numberToWordsHelper(int num) {
            String result = "";
            Map.Entry<Integer, String> floorEntry = numMap.floorEntry(num);
            int key = floorEntry.getKey();
            int remain = 0;
            if (key >= 100) {
                result = numberToWordsHelper(num / key) + ' ';
                remain = num - (num / key) * key;
            } else {
                remain = num - key;
            }
            result = result + floorEntry.getValue();
            if (remain > 0) {
                result = result + ' ' + numberToWordsHelper(remain);
            }
            return result;
        }
        
        private void setup() {
            numMap.put(1000000000, "Billion");
            numMap.put(1000000, "Million");
            numMap.put(1000, "Thousand");
            numMap.put(100, "Hundred");
            numMap.put(90, "Ninety");
            numMap.put(80, "Eighty");
            numMap.put(70, "Seventy");
            numMap.put(60, "Sixty");
            numMap.put(50, "Fifty");
            numMap.put(40, "Forty");
            numMap.put(30, "Thirty");
            numMap.put(20, "Twenty");
            numMap.put(19, "Nineteen");
            numMap.put(18, "Eighteen");
            numMap.put(17, "Seventeen");
            numMap.put(16, "Sixteen");
            numMap.put(15, "Fifteen");
            numMap.put(14, "Fourteen");
            numMap.put(13, "Thirteen");
            numMap.put(12, "Twelve");
            numMap.put(11, "Eleven");
            numMap.put(10, "Ten");
            numMap.put(9, "Nine");
            numMap.put(8, "Eight");
            numMap.put(7, "Seven");
            numMap.put(6, "Six");
            numMap.put(5, "Five");
            numMap.put(4, "Four");
            numMap.put(3, "Three");
            numMap.put(2, "Two");
            numMap.put(1, "One");
        }
    }

Log in to reply
 

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