My easy understanding java solution with hashmap


  • 0
    Z
    public class Solution {
        public String numberToWords(int num) {
            Map<Integer, String> map = new HashMap<Integer, String>();
            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, "`enter code here`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");
            String res = "";
            int[] number = new int[4];
            String[] word = new String[4];
            number[0] = 1000000000;
            number[1] = 1000000;
            number[2] = 1000;
            number[3] = 1;
            word[0] = "Billion";
            word[1] = "Million";
            word[2] = "Thousand";
            word[3] = "";
            if(num==0){
                return "Zero";
            }
            for(int i=0; i<4; i++){
                if(num>=number[i]){
                    res+=inThousand(num/number[i], map)+word[i]+" ";
                }
                num = num%number[i];
                if(num==0){
                    break;
                }
            }
            int i = res.length();
            while(i>0&&res.charAt(i-1)==' '){
                i--;
            }
            return res.substring(0, i);
        }
        private String inThousand(int num, Map<Integer, String> map){
            String res = "";
            if(num==0){
                return "";
            }
            if(num>=100){
                res+=map.get(num/100)+" Hundred ";
            }
            num = num%100;
            if(num==0){
                return res;
            }
            if(map.containsKey(num)){
                return res+=map.get(num)+" ";
            }
            res+= map.get(num-num%10)+" ";
            num = num%10;
            if(num==0){
                return res;
            }
            return res+map.get(num)+" ";
        }
    }

Log in to reply
 

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