将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
    示例 1:
    **
    输入: 123
    输出: “One Hundred Twenty Three”

    示例 2:
    **
    输入: 12345
    输出: “Twelve Thousand Three Hundred Forty Five”

    示例 3:
    **
    输入: 1234567
    输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

    示例 4:
    **
    输入: 1234567891
    输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/integer-to-english-words

    思路:
    观察示例可知:可将其按照每3位分割一次,例如12345 -> 12,345,英文则为** **``Twelve,Thousand,Three Hundred Forty Five,转换为对1000以内数字的英文转换,再处理一下Thousand,Million,Billion 对应的位置就ok了。
    复杂度分析:
    时间复杂度O(n)
    空间复杂度O(1)

    1. var numberToWords = function (num) {
    2. if (num === 0) return "Zero";
    3. const LESS_THAN_TWENTY = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
    4. const TWENTY = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
    5. const THOUSAND = ["", "Thousand", "Million", "Billion"];
    6. const helper = (num) => {
    7. if (num === 0) return "";
    8. let str = "";
    9. if (num >= 100) {
    10. str += LESS_THAN_TWENTY[Math.floor(num / 100)] + " Hundred ";
    11. num %= 100;
    12. }
    13. if (num < 100 && num >= 20) {
    14. str += TWENTY[Math.floor(num / 10)] + " ";
    15. num %= 10;
    16. }
    17. if (num < 20 && num > 0) {
    18. str += LESS_THAN_TWENTY[num] + " ";
    19. }
    20. return str;
    21. };
    22. let ans = "";
    23. let index = 0;
    24. while (num > 0) {
    25. if (num % 1000 !== 0) {
    26. let str = helper(num % 1000);
    27. ans = str + THOUSAND[index] + " " + ans;
    28. }
    29. index++;
    30. num = Math.floor(num / 1000);
    31. }
    32. return ans.trim();
    33. };