Integer to English Words

来源:互联网 发布:手机注册淘宝小号 编辑:程序博客网 时间:2024/05/22 01:41

此题当中有很多要注意的点:

1. 各个字符数组的开头,都是空字符串;

2. less100的下标第1个字符串是空的;

3. 各个不同的空格;

4. 最后返回res得做trim()处理;

5. helper中的helper递归调用都是放在结尾的;

6. 还是背一背吧,哈哈

public class Solution {    private final String[] less20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};    private final String[] less100 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};    private final String[] more100 = {"", "Thousand", "Million", "Billion"};    public String numberToWords(int num) {        if (num == 0) {            return "Zero";        }        int i = 0;        String res = "";        while (num > 0) {            if (num % 1000 != 0) {                res = helper(num % 1000) + more100[i] + " " + res;            }            num = num / 1000;            i++;        }                return res.trim();    }        private String helper(int num) {        if (num == 0) {            return "";        } else if (num < 20) {            return less20[num] + " ";        } else if (num < 100) {            return less100[num/10] + " " + helper(num%10);        } else {            return less20[num/100] + " Hundred " + helper(num%100);        }    }}



0 0
原创粉丝点击