PAT - 甲级 - 1082. Read Number in Chinese (25)(字符串处理)

本文介绍了一种用C++实现将负数转换为传统中文读法的方法。针对不超过9位数的整数,程序能够正确处理零及万等特殊读法,并提供了完整的代码示例。

摘要生成于 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


给定条件:
1.给定一个整数

要求:
1.“读出”这个数

求解思路:
1.先试着每个数字都读出来,找出错误的地方
2.发现ling和wan需要特殊处理
4.依次处理每一位,需要特殊处理的增加判断条件即可
5.具体看代码


#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

int n;
vector<string> v;
string num[10] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};

int main() {
	scanf("%d", &n);
	if(n == 0){
		printf("ling\n");
		return 0;
	}

	if(n < 0) {
		n *= -1;
		printf("Fu ");
	}

	int cnt = 0;
	while(n > 0) {
		switch(cnt){
			case 1 : if(n%10)v.push_back("Shi"); break;
			case 2 : if(n%10)v.push_back("Bai"); break;
			case 3 : if(n%10)v.push_back("Qian"); break;
			case 4 : if(n%10 || n/10%10 || n/10/10%10 || n/10/10/10%10)v.push_back("Wan"); break;
			case 5 : if(n%10)v.push_back("Shi"); break;
			case 6 : if(n%10)v.push_back("Bai"); break;
			case 7 : if(n%10)v.push_back("Qian"); break;
			case 8 : if(n%10)v.push_back("Yi"); break;
		}
		if(n%10 == 0) {
			if(!v.empty() && v[v.size()-1] != "ling" ) {
				if(v[v.size()-1] != "Shi" && v[v.size()-1] != "Bai" && v[v.size()-1] != "Qian" && v[v.size()-1] != "Wan")
				v.push_back(num[n%10]);
			}
		}else {
			v.push_back(num[n%10]);	
		}
		cnt++;
		n /= 10;
	}

	for(int i = v.size()-1; i > 0; i--){
		printf("%s ", v[i].c_str());
	}
	printf("%s\n", v[0].c_str());
	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}'") ``` 这段程序通过分段处理大数,并利用递归来简化子问题求解过程。它能够有效地应对各种边界情况,确保输出结果既简洁又准确地反映了输入数字所代表的真实含义。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值