Tuesday, September 8, 2015

Leetcode: Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Hint:
  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
  3. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
Code (Java):
public class Solution {
    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        
        Map<Integer, String> map = new HashMap<>();
        // Step 1: fill the hash map
        fillHashMap(map);
    
        StringBuffer sb = new StringBuffer();
        int groupId = 1;
        
        // Step 2: group the num with 3 digits
        while (num > 0) {
            int group = num % 1000;
            
            if (groupId > 1 && group > 0) {
                String groupStr = getGroupName(groupId);
                sb.insert(0, groupStr);
            }
            
            String str = numberToWordsHelper(group, map);
            sb.insert(0, str);
            
            groupId++;
            num /= 1000;
        }
        
        String result = sb.toString();
        if (result.charAt(result.length() - 1) == ' ') {
            return result.substring(0, result.length() - 1);
        } else {
            return result;
        }
    }
    
    private void fillHashMap(Map<Integer, String> map) {
        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 ");
        map.put(100, "One Hundred ");
        map.put(1000, "One Thousand ");
    }
    
    private String getGroupName(int groupId) {
        String result = null;
        switch(groupId) {
            case 2: result = "Thousand ";
            break;
            
            case 3: result = "Million ";
            break;
            
            case 4: result = "Billion ";
            break;
        }
        
        return result;
    }
    
    private String numberToWordsHelper(int num, Map<Integer, String> map) {
        int pos = 0;
        StringBuffer sb = new StringBuffer();
        
        if (num <= 0) {
            return "";
        }
        
        int tmp = num;
        while (tmp > 0) {
            pos++;
            tmp /= 10;
        }
        
        while (num > 0) {
            if (num <= 20) {
                sb.append(map.get(num));
                break;
            }
            
            int digit = num / (int) Math.pow(10, pos - 1);
            int curr = digit * (int) Math.pow(10, pos - 1);
            
            if (pos == 3) {
                sb.append(map.get(digit));
                sb.append("Hundred ");
            } else {
                sb.append(map.get(curr));
            }
            
            num = num % (int) Math.pow(10, pos - 1);
            pos--;
        }
        
        return sb.toString();
    }
}

A neat solution without using HashMap. 
public class Solution {
    public String numberToWords(int num) {
        if (num == 0) {
            return "Zero";
        }
        
        String[] group = {"", "Thousand ", "Million ", "Billion "};
        String[] dict1 = {"", "One ", "Two ", "Three ", "Four ", 
                          "Five ", "Six ", "Seven ", "Eight ", "Nine ",
                          "Ten ", "Eleven ", "Twelve ", "Thirteen ",
                          "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ",
                          "Eighteen ", "Nineteen "};
        String[] dict2 = {"", "", "Twenty ", "Thirty ", "Forty ", "Fifty ",
                          "Sixty ", "Seventy ", "Eighty ", "Ninety "};
        
        StringBuffer sb = new StringBuffer();
        
        for (int i = 0; i < 4; i++) {
            int curr = num % 1000;
            if (curr > 0) {
                if (i > 0) {
                    sb.insert(0, group[i]);
                }
                sb.insert(0, numToWordsHelper(curr, dict1, dict2));
            }
            num /= 1000;
        }
        
        String result = sb.toString();
        if (result.charAt(result.length() - 1) == ' ') {
            return result.substring(0, result.length() - 1);
        } else {
            return result;
        }
    }
    
    private String numToWordsHelper(int num, String[] dict1, String[] dict2) {
        StringBuffer result = new StringBuffer();
        
        int a = num / 100;
        int b = num % 100;
        int c = num % 10;
        
        if (a > 0) {
            result.append(dict1[a] + "Hundred ");
        }
        
        if (b > 0 && b < 20) {
            result.append(dict1[b]);
            c = 0; 
        } else if (b >= 20) {
            b /= 10;
            result.append(dict2[b]);
        }
        
        if (c > 0) {
            result.append(dict1[c]);
        }
        
        return result.toString();
    }
}

Summary:
There are some corner cases need to be very careful:
input = 1000, output = One Thousand, not One Thousand Zero
input = 1,000,000, output is One million , not One Million Thousand.  

No comments:

Post a Comment