Easy To Understand Recursion


  • 0
    N
    public class Solution {
        Map<Integer,String> map;
        String[] flags = {"Billion", "Million", "Thousand", "Hundred"};
        int[] nums = {(int)Math.pow(10,9),(int)Math.pow(10,6), 1000, 100};
        public String numberToWords(int num) {
            if(num == 0) {
                return "Zero";
            }
            map = initMap();
            return parse(num,0);
        }
        String parse(int num, int start) {
            if(num > 0 && num < 100) {
                if (map.containsKey(num)) {
                    return map.get(num);
                } else {
                    int n = num / 10;
                    return map.get(n * 10) + " " + map.get(num - n * 10);
                }
            }
            StringBuilder sb = new StringBuilder();
            int t = num / nums[start];
            if (t > 0) {
                sb.append(parse(t,0) + " " + flags[start]);
                num = num - t * nums[start];
            }
            if(num > 0) {
                sb.append(sb.length() == 0 ? "" : " ");
                sb.append(parse(num,start + 1));
            }
            return sb.toString();
        }
        Map<Integer,String> initMap() {
            Map<Integer,String> map = new HashMap<>();
            map.put(0,"Zero");
            map.put(1,"One");
            map.put(2,"Two");
            map.put(3,"Three");
            map.put(4,"Four");
            map.put(5,"Five");
            map.put(6,"Six");
            map.put(7,"Seven");
            map.put(8,"Eight");
            map.put(9,"Nine");
            map.put(10,"Ten");
            map.put(11,"Eleven");
            map.put(12,"Twelve");
            map.put(13,"Thirteen");
            map.put(14,"Fourteen");
            map.put(15,"Fifteen");
            map.put(16,"Sixteen");
            map.put(17,"Seventeen");
            map.put(18,"Eighteen");
            map.put(19,"Nineteen");
            map.put(20,"Twenty");
            map.put(30,"Thirty");
            map.put(40,"Forty");
            map.put(50,"Fifty");
            map.put(60,"Sixty");
            map.put(70,"Seventy");
            map.put(80,"Eighty");
            map.put(90,"Ninety");
            return map;
        }
    }

Log in to reply
 

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