AdSense

Saturday, October 8, 2016

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"

Numbers are always partitioned by three digits. For example, 123456789 can be written as 123,456,789, and is read as one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine. Thus we can convert the numbers three digits by three digits, Every time we divide the number by one thousand. If the reminder of mod 1000 is greater than zero, we convert the three digits to hundreds and add correct digit to it. Be careful about zeros and spaces.


private static String[] numbers = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private static String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private static String[] digits = {"Thousand", "Million", "Billion"};
    
    public String numberToWords(int num) {
        String rst = convertToHundreds(num % 1000);
        for (int i = 0; i < 3; i++) {
            num /= 1000;
            rst = num % 1000 > 0 ? convertToHundreds(num % 1000) + " " + digits[i] + " " + rst : rst;
        }
        
        return rst.length() == 0 ? "Zero" : rst.trim();
    }
    
    private String convertToHundreds(int num) {
        int a = num / 100, b = num % 100, c = num % 10;
        String rst = a > 0 ? numbers[a] + " Hundred " : "";
        rst += b <= 19 ? numbers[b] : (tens[b / 10] + " " + (c > 0 ? numbers[c] : ""));
        return rst.trim();
    }


No comments:

Post a Comment