leetcode:273. 整数转换英文表示

题目

将非负整数 num 转换为其对应的英文表示。
提示:0 <= num <= 2^31 - 1

示例:

  1. 输入:num = 123
  2. 输出:"One Hundred Twenty Three"
  1. 输入:num = 12345
  2. 输出:"Twelve Thousand Three Hundred Forty Five"
  1. 输入:num = 1234567
  2. 输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

解答 & 代码

模拟,三位一组进行转换

  1. class Solution {
  2. public:
  3. string numberToWords(int num) {
  4. unordered_map<int, string> map {{1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"},
  5. {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, {9, "Nine"},
  6. {10, "Ten"}, {11, "Eleven"}, {12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"},
  7. {15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"}, {18, "Eighteen"}, {19, "Nineteen"},
  8. {20, "Twenty"}, {30, "Thirty"}, {40, "Forty"}, {50, "Fifty"}, {60, "Sixty"},
  9. {70, "Seventy"}, {80, "Eighty"}, {90, "Ninety"}};
  10. vector<string> part = {"", "Thousand", "Million", "Billion"};
  11. // 存储整数的每一位数值(逆序)
  12. vector<int> number;
  13. while(num > 0)
  14. {
  15. number.push_back(num % 10);
  16. num /= 10;
  17. }
  18. int len = number.size();
  19. string result; // 结果字符串
  20. int idx = len - 1;
  21. while(idx >= 0) // 每次 3 个数字一组进行迭代
  22. {
  23. int partIdx = idx / 3; // 代表当前三位是 0、千、百万、十亿 级别
  24. bool zero = true; // 代表当前三位是否都为 0
  25. // 处理当前三位的百位
  26. if(idx % 3 == 2)
  27. {
  28. if(number[idx] != 0)
  29. {
  30. result += map[number[idx]];
  31. result += " Hundred ";
  32. zero = false;
  33. }
  34. --idx;
  35. }
  36. bool ten = false; // 代表十位是否为 1
  37. // 处理当前三位的十位
  38. if(idx % 3 == 1)
  39. {
  40. if(number[idx] == 1)
  41. {
  42. ten = true;
  43. zero = false;
  44. }
  45. else if(number[idx] > 1)
  46. {
  47. result += map[number[idx] * 10];
  48. result += " ";
  49. zero = false;
  50. }
  51. --idx;
  52. }
  53. // 处理当前三位的个位
  54. if(idx % 3 == 0)
  55. {
  56. int cur = number[idx];
  57. if(ten == true) // 若十位为 1,则和个位一起处理
  58. cur += 10;
  59. if(cur != 0)
  60. {
  61. result += map[cur];
  62. result += " ";
  63. zero = false;
  64. }
  65. --idx;
  66. }
  67. // 若当前三位数字不都为 0,则加上 0/千/百万/十亿 后缀
  68. if(zero == false)
  69. {
  70. result += part[partIdx];
  71. result += " ";
  72. }
  73. }
  74. // 去掉结果的后缀空格
  75. for(int i = result.size() - 1; i >= 0 && result[i] == ' '; --i)
  76. result.pop_back();
  77. // 如果结果数组为空,则为 Zero
  78. if(result.size() == 0)
  79. result = "Zero";
  80. return result;
  81. }
  82. };

复杂度分析:

  • 时间复杂度 O(1):3 位一组,最多 4 组,因为 num <= 2^31 - 1
  • 空间复杂度 O(1):结果字符串不计入。哈希表存储的是常数级别的

执行结果:

  1. 执行结果:通过
  2. 执行用时:4 ms, 在所有 C++ 提交中击败了 69.29% 的用户
  3. 内存消耗:7.8 MB, 在所有 C++ 提交中击败了 11.28% 的用户