题解 | #学英语#

学英语

https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc

#include <stdio.h>
#include <string.h>

void ShowSinglePart(int num);
void GetInputAndShow();

int main() {
    GetInputAndShow();
    return 0;
}

//一些可能的输入和输出
//数字范围: [1, 2,000,000]
//22: twenty two
//100: one hundred
//145:  one hundred and forty five
//1,234:  one thousand two hundred and thirty four
//8,088:  eight thousand (and) eighty eight (注:这个and可加可不加,这个题目我们选择不加)
//486,669:  four hundred and eighty six thousand six hundred and sixty nine
//特点:
//Xbillion--Xmillion---Xthousand---X
//X代表1、2、3位数,如果有百位,中间要有and

//思路
//1. 将输入的数字,转换为字符串。
//2. 确定字符串的长度 范围如下[1,3]不加 [4,6]加thousand [7,9]加million [10,12]billion
//3. 将字符串从低分割成 3 个字符(数字)一组。每组先独立转换.
//4. 将上面的组合起来,例外:如果3个字符均为0,那么直接删去后缀。
//输入一个数字,输出一个字符串
char sdigit[][10] = {"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
//如果首位是1,且个位不是0
char cdigit_ten[][10] = {"zero", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
//如果首位不是1 或者 是1但个位是0
char cdigit[][10] = {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
char andstr[] ="and";
char hundredstr[] = "hundred";
char thstr[] = "thousand";
char mlnstr[] = "million";
char blnstr[] = "billion";

void ShowSinglePart(int num)
{
    char buf[100] = {0};
    char *p = buf;
    //将百位、十位、个位分别得到
    char bai = 0;
    char shi = 0;
    char ge = 0;
    
    ge = num%10;
    shi = (num/10)%10;
    bai = num/100;
    if(bai != 0)//百位的处理
    {
        strcat(buf,sdigit[bai]);
        strcat(buf, " ");
        strcat(buf, hundredstr);
        if(shi!=0 || ge!=0)
        {
            strcat(buf, " ");
            strcat(buf, andstr);
            strcat(buf, " ");
        }

    }
    if(shi!=0)//十位的处理
    {
        if(shi!=1)
        {
            strcat(buf, cdigit[shi]);
            if(ge!=0)strcat(buf, " ");
        }
        else if((shi == 1) && (ge==0))
        {
            strcat(buf,cdigit[shi]);
            if(ge!=0)strcat(buf, " ");
        } 
        else
        {
            strcat(buf,cdigit_ten[ge]);
        }
    }
    if((shi!=1)&&(ge!=0))//个位的处理
    {
        strcat(buf, sdigit[ge]);
    }
    printf("%s", buf);
}


void GetInputAndShow()
{
    long temp = 0;
    int blnpart = 0;
    int mlnpart = 0;
    int thpart = 0;
    int finalpart = 0;
    scanf("%ld", &temp);
 
  	//求出各部分值
    blnpart =temp/1000000000;
    mlnpart = temp%1000000000/1000000;
    thpart = temp%1000000/1000;
    finalpart = temp%1000;
    int fourpart[4] = {blnpart, mlnpart, thpart, finalpart};
    char foursufix[4][10] = {"billion", "million", "thousand", ""};
    for(int i=0; i<4; i++)
    {
        if(fourpart[i]!=0)
        {
            ShowSinglePart(fourpart[i]);
            printf(" %s ", foursufix[i]);
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务