【Leetcode】273. Integer to English Words

题目地址:

https://leetcode.com/problems/integer-to-english-words/

将一个十进制 32 32 32位非负整数转为其英语表达。

先开个函数专门求一下一个 1 ∼ 999 1\sim 999 1999的英文表达,然后对原数拆解为多少个billion,多少个million和多少个thousand,最后拼接起来。代码如下:

class Solution {
 public:
  vector<string> n0_19 = {"Zero",    "One",       "Two",      "Three",
                          "Four",    "Five",      "Six",      "Seven",
                          "Eight",   "Nine",      "Ten",      "Eleven",
                          "Twelve",  "Thirteen",  "Fourteen", "Fifteen",
                          "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

  vector<string> n20_90 = {"Twenty", "Thirty",  "Forty",  "Fifty",
                           "Sixty",  "Seventy", "Eighty", "Ninety"};

  vector<string> n1000 = {" Billion ", " Million ", " Thousand ", ""};

  string numberToWords(int num) {
    if (num == 0) return "Zero";
    string res;
    for (int i = 1e9, j = 0; i >= 1; i /= 1000, j++)
      if (num >= i) {
        res += get(num / i) + n1000[j];
        num %= i;
      }

    if (res.back() == ' ') res.pop_back();
    return res;
  }

  // 得到1~999的英文表示
  string get(int x) {
    string res;
    if (x >= 100) {
      res += n0_19[x / 100] + " Hundred ";
      x %= 100;
    }
    if (x >= 20) {
      res += n20_90[x / 10 - 2] + ' ';
      x %= 10;
      if (x != 0) res += n0_19[x];
    } else if (x > 0)
      // 如果是0的话是不要将“Zero”拼在后面的
      res += n0_19[x];

    if (res.back() == ' ') res.pop_back();
    return res;
  }
};

时空复杂度 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值