PAT A1082. Reading Number in Chinese

本文详细解析了如何将一个不超过九位数的整数用传统中文方式读出,并特别注意处理数字0的情况。通过具体实例介绍了不同场景下0的正确读法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese way. Output "Fu" first if it is negative. For example, -123456789 is read as "Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu". Note: zero ("ling") must be handled correctly according to the Chinese tradition. For example, 100800 is "yi Shi Wan ling ba Bai".

Input Specification:

Each input file contains one test case, which gives an integer with no more than 9 digits.

Output Specification:

For each test case, print in a line the Chinese way of reading the number. The characters are separated by a space and there must be no extra space at the end of the line.

Sample Input 1:
-123456789
Sample Output 1:
Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu
Sample Input 2:
100800
Sample Output 2:

yi Shi Wan ling ba Bai


/****************************************侯尼玛****************************************/

思路:

做这道题最开始时的思路是把每四位数字独立拿出来做“千百十”的输出,然后分别输出“亿”和“万”。反复修改提交以后倒数第二个测试例始终通不过。想了很久,很惭愧最后还是去牛客网提交了一下,看了上面具体的测试例内容,然后换了一个新的思路:从高位到低位输出,在模4余0的特殊位上(首位为0)分别输出“yi”(亿位)“wan”(万位)和“\0”(个位)

仔细分析,可以发现核心的问题还是对0的处理,分这几种情况:

(1)一段连续的0,如果没有一个0是在特殊位上,则遍历到的第一个非0数字时输出ling————例如10001

(2)一段连续的0,遍历到的当前0在特殊位上,且该特殊位至前一个特殊位之间有非0数字,则直接输出特殊位的值“yi或wan或\0”,不输出“ling”————例如110001000

(这点有些奇怪,但是在牛客网上确实有这么一个测试例:-10301234,对应的输出是Fu yi Qian ling san Shi Wan yi Qian er Bai san Shi si)

(另外,如果在特殊位之后紧接0,属于第二种情况+第一种情况————例如11000+0100)

(3)一段连续的0,遍历到的当前0在特殊位上,且该特殊位至前一个特殊位之间没有非0数字,则很像第一种情况,不输出特殊位的值,直接向下遍历,直到遇到下一个非0数字时输出ling————例如100001000以及100000100

(4)单独给出的一个0,要求输出是ling。

因此要针对这四种情况分别处理,就能全AC了。

贴一下我的代码:

#include <iostream>
#include <string>
using namespace std;

void ChinesePrint(string str,int length)
{
    string ReadNounce[9]={"yi","er","san","si","wu","liu","qi","ba","jiu"};
    string Wei[3]={"\0"," Wan"," Yi"};
    bool LingBool = false;//判断是否有0
    bool Start=true;//判断是否第一位数字
    bool HasNum = false;//判断在两个特殊位之间是否有非0数字
    int i = length-1;//从高位至低位遍历
    while(i>=0)
    {
        if(str[i]=='0')
        {
            LingBool=true;
            if(i%4==0 && HasNum)//如果当前的0处在特殊位,且有非0数字,则适用第二种情况
            {
                cout<<Wei[i/4];
                LingBool=false;//输出特殊位之后要重置LingBool,不影响下一个特殊位之后的0。
                HasNum=false;
            }
            i--;
            continue;//如果不是在特殊位,跳过这一个0,查看下一位数字。
        }

        if(!Start)//如果到了这一行,说明当前位的数字不是0,可以正常依格式输出了,如果LingBool为true的话属于第一或第三种情况,要输出ling
            cout<<' ';
        if(LingBool && !Start)
        {
            cout<<"ling";
            LingBool=false;
            continue;
        }
        Start=false;
        cout<<ReadNounce[(str[i]-'0'-1)];//通过string数组输出数字对应的拼音
        HasNum=true;
        LingBool=false;

        switch (i%4)
        {
        case 3:
            {
                cout<<" Qian";
                break;
            }
        case 2:
            {
                cout<<" Bai";
                break;
            }
        case 1:
            {
                cout<<" Shi";
                break;
            }
        case 0:
            {
                if(HasNum)
                {
                    cout<<Wei[i/4];
                    LingBool=false;
                    HasNum=false;
                }
                break;
            }
        }
        i--;
    }
}

int main()
{
    string LongNum;
    while(cin>>LongNum)
    {
        int length = LongNum.size();
        string ReverseNum(LongNum);
        int i;
        for(i=0;i<length;i++)
        {
            ReverseNum[i]=LongNum[length-1-i];
        }
        if(ReverseNum[length-1]=='-')
        {
            cout<<"Fu ";
            ReverseNum[length]='\0';
            length--;
        }
        for(int i=length-1;i>0;i++)
        {
            if(ReverseNum[i]=='0')
            {
                ReverseNum[length]='\0';
                length--;
            }
            else break;
        }
        if(length ==1 && ReverseNum[0]=='0')//这道题很贱的一点是,单独给出的一个0,要求输出是ling
                cout<<"ling";
        else
            ChinesePrint(ReverseNum,length);
    }
    return 0;
}


### 中文数字读取算法解析 对于 PAT 1082 题目中的 `Read Number in Chinese` 功能,核心在于将阿拉伯数字转换成符合汉语习惯的表达方式。具体来说,需要处理不同位数下的单位以及特殊情况,比如连续多个零只读作一个零。 为了实现这一功能,在代码逻辑上需要注意以下几个方面: - **单位映射**:建立数组来存储各个数量级对应的汉字名称。 - **特殊字符处理**:“十”是一个特殊的量词,当数值小于二十时需特别对待。 - **去除冗余零**:按照汉语发音规则,连续出现的零只需念一次;位于整万、整亿前后的零也需要适当省略。 下面给出一段 Python 版本的具体实现示例[^1]: ```python def read_number_in_chinese(num_str): units = ["", "万", "亿"] digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'] tens_units = ['', '十', '百', '千'] def process_chunk(chunk, unit_suffix=""): chunk_result = [] length = len(chunk) for i in range(length): digit_value = int(chunk[length - 1 - i]) if digit_value != 0 or (i == length - 1 and not all(c == '0' for c in chunk)): if i > 0: chunk_result.append(tens_units[i]) chunk_result.append(digits[digit_value]) result = ''.join(reversed(chunk_result)).strip() # Remove redundant zeros at the end of each chunk except when it's a single zero. while len(result) >= 2 and result.endswith('零'): result = result[:-1] if result.startswith('一十') and len(result) > 2: result = result[1:] return f"{result}{unit_suffix}" if result else "" num_parts = [] # Split into chunks based on billions and millions. for idx, part in enumerate([num_str[max(i - 4, 0):i][::-1] for i in range(len(num_str), 0, -4)]): processed_part = process_chunk(part[::-1], units[idx % 3]) if processed_part: num_parts.insert(0, processed_part) final_result = "".join(num_parts).replace("亿万", "亿").replace("零万", "").replace("零亿", "") # Handle leading zeroes across different sections. while "零零" in final_result: final_result = final_result.replace("零零", "零") if final_result.startswith("一十") and len(final_result) > 2: final_result = final_result[1:] if not final_result: return "零" elif final_result[-1:] == "零": return final_result[:-1] else: return final_result if __name__ == "__main__": test_cases = [ ("102345", "十万零两千三百四十五"), ("100002345", "一亿零两千三百四十五") ] for case, expected_output in test_cases: actual_output = read_number_in_chinese(case) print(f"Input: {case}, Expected Output: '{expected_output}', Actual Output: '{actual_output}'") ``` 这段程序通过分段处理大数,并利用递归来简化子问题求解过程。它能够有效地应对各种边界情况,确保输出结果既简洁又准确地反映了输入数字所代表的真实含义。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值