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"
思路
  1. 题目首先告诉我们要3个一组的进行处理,而且限定了输入数字范围为0到231 - 1之间,最高只能到billion位,3个一组也只需处理四组即可,那么我们需要一个处理三个一组数字的函数。
  2. 需要把1到9,10 - 19的英文单词都列出来,分别放到2个数组里;还要把20,30,... 到90的英文单词列出来放到另一个数组里。
  3. 然后我们需要用技巧,比如一个三位数n
    • 百位数表示为n/100
    • 后两位数一起表示为n%100
    • 十位数表示为n%100/10
    • 个位数表示为n%10
  4. 然后我们看后两位数是否小于10 或者小于20,小于的话直接从数组中取出单词
  5. 如果大于等于20的话,则分别将十位和个位数字的单词从两个数组中取出来。
  6. 然后再来处理百位上的数字,还要记得加上Hundred。然后中间要插入"Thousand", "Million", "Billion"到对应的位置
  7. 最后check一下末尾是否有空格,把空格都删掉

Coner Case: 检查下输入是否为0 或者小于0,是的话要返回'Zero' 或者NULL。

class Solution {
    String[] belowTen = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
        String[] teens = {"Ten", "Eleven", "Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        String[] belowHundreds = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
        
    public String numberToWords(int num) {
        if (num < 0) return null;
        if (num == 0) return "Zero";
        return helper(num);
    }
    
    public String helper(int num) {
        String result = new String();
        if (num < 10) {
            result = belowTen[num];
        } else if (num < 20) {
            result = teens[num % 10];
        } else if (num < 100) {
            result = belowHundreds[num / 10] + " " + belowTen[num % 10];
        } else if (num < 1000) {
            result = belowTen[num / 100] + " Hundred " + helper(num % 100);
        } else if (num < 1000000) {
            result = helper(num / 1000) + " Thousand " + helper(num % 1000);
        } else if (num < 1000000000) {
            result = helper(num / 1000000) + " Million " + helper(num % 1000000);
        } else {
            result = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
        }
        return result.trim();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容