LeetCode刷题273-困难-整数转换成英文

96 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

☀️ 前言 ☀️

算法作为极其重要的一点,是大学生毕业找工作的核心竞争力,所以为了不落后与人,开始刷力扣算法题!

🙀 作者简介 🙀

大家好,我是布小禅,一个尽力让无情的代码变得生动有趣的IT小白,很高兴能偶认识你,关注我,每天坚持学点东西,我们以后就是大佬啦!

这是我刷第 80/100 道力扣简单题

💗 一、题目描述 💗

将非负整数 num 转换为其对应的英文表示。

示例1:

输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"

示例2:

输入:num = 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

提示:0 <= num <= 231 - 1

💁 二、题目解析 💁

思路1\color{green}{思路1:}

  \- 把思路缕清晰

  \- 先把英文表示的数字表达出来

  \- 然后诸位分析

🏃 三、代码 🏃

☁️ C语言☁️

/*
  - 把思路缕清晰
  - 先把英文表示的数字表达出来
  - 然后诸位分析
*/

const char *ge[] = {
    "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
};
const char *shi1[] = {
    "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
};
const char *shi2[] = {
    "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
};

#define N 2000
char result[N] = { 0 };
bool appended = false;

void baishige(int n)
{
    int b = (n / 100) % 10;
    n %= 100;
    if (b) { // 百位
        if (appended) {
            strcat(result, " ");
        }
        strcat(result, ge[b]);
        strcat(result, " Hundred");
        appended = true;
    }
    int s = n / 10;
    n %= 10;
    if (s) { // 十位
        if (appended) {
            strcat(result, " ");
        }
        if (s == 1) {
            strcat(result, shi1[n]);
            n = 0; // 不需要再看个位了
        } else {
            strcat(result, shi2[s]);
        }
        appended = true;
    }
    if (n) { // 个位
        if (appended) {
            strcat(result, " ");
        }
        strcat(result, ge[n]);
        appended = true;
    }
}

#define BILLION 1000000000
#define MILLION 1000000
#define THOUSAND 1000
char *numberToWords(int n)
{
    if (n <= 0) {
        strcpy(result, "Zero");
        return result;
    }
    appended = false;
    memset(result, 0, sizeof(result));
    int b = n / BILLION;
    n %= BILLION;
    if (b) { // BILLION
        baishige(b);
        strcat(result, " Billion");
    }
    int m = n / MILLION;
    n %= MILLION;
    if (m) { // MILLION
        baishige(m);
        strcat(result, " Million");
    }
    int t = n / THOUSAND;
    n %= THOUSAND;
    if (t) { // 千位
        baishige(t);
        strcat(result, " Thousand");
    }
    baishige(n);
    return result;
}


🌔 结语 🌔

坚持最重要,每日一题必不可少!:smile_cat:

期待你的关注和督促!:stuck_out_tongue:

在这里插入图片描述