Friday, December 18, 2015

Integer to English Words

Q:
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"
A:
就是递归调用

public class Solution {
    
    public static String[] Tens = {"Ten","Twenty","Thirty","Forty", "Fifty","Sixty","Seventy","Eighty","Ninety"};
    public static String[] Teens = {"Eleven","Twelve","Thirteen","Fourteen", "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    public static String[] Ones = {"One","Two", "Three","Four","Five","Six","Seven","Eight","Nine"};
    public String numberToWords(int num) {
        if(num==0)
            return "Zero";
        return helper(num).trim();
    }
    private String helper(int num){
        if((int)(num / Math.pow(10,9)) > 0){
            return helper((int)(num/Math.pow(10,9)))+"Billion " + helper((int)(num % Math.pow(10,9)));
        }
        if((int)(num / Math.pow(10,6)) > 0){
            return helper((int)(num/Math.pow(10,6)))+"Million " + helper((int)(num % Math.pow(10,6)));
        }
        if(num/1000 > 0){
            return helper(num/1000)+"Thousand " + helper(num % 1000);
        }
        if(num / 100 > 0){
            return helper(num/100)+"Hundred " + helper(num % 100);
        }
        if(num>10 && num< 20)
            return Teens[num-11] +" ";
        if(num/10>0){
            return Tens[num/10-1] + " " +helper(num % 10);
        }
        if(num>0)
            return Ones[num-1]+" ";
        return "";
    }
}
Mistakes:

  1. 用 num / Math.pow(10,9)的时候, 结果是double类型的,因此,作为参数传递的时候,会有报错。double to int 
  2. 没有考虑 11- 19的情况。
  3. 90 是“ninety”, 而不是“ninty”.   19  是 ”nineteen“  而不是”ninteen“。  丢人啊



No comments:

Post a Comment