PAT甲级 1082(C++)

好久没刷PAT了,终于把这道搁置的题解决了Q_Q

测试点三要考虑的是一个0的问题,即输入0或-0,应该输出ling或Fu ling

主要思路:将输入字符串4个分为一组输出。如果遇到第一个0,则将zero_flag置为1,直到遇到下一个非0元素,再将zero_flag置为0。zero_flag为1期间,不对字符串内容进行统计,当zero_flag由1变为0时,将ling加入待输出的字符串(可以避免800输出ba Bai ling,避免100800输出yi shi ling Wan ba Bai ling,将0输出的位置调整到Wan之后,同时800后的0不输出)

AC代码:

#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
map<int, string>unit;
map<int, string>nums;
int main() {
	vector<string>result;
	string number; cin >> number;
	unit[0] = ""; unit[1] = "Shi"; unit[2] = "Bai"; unit[3] = "Qian";; unit[4] = "Wan"; unit[5] = "Yi";
	nums[0] = "ling"; nums[1] = "yi"; nums[2] = "er"; nums[3] = "san"; nums[4] = "si";
	nums[5] = "wu"; nums[6] = "liu"; nums[7] = "qi"; nums[8] = "ba"; nums[9] = "jiu";
	if (number[0] == '-') {
		result.push_back("Fu");
		number.erase(number.begin());
	}
	int i = number.size() % 4;
	int group = number.size() / 4+(i!=0);
	int zero_flag = 0;
	if (number.size() == 1 && number[0] == '0') result.push_back(nums[0]);
	while (number.size()!=0) {
		if (i == 0) i = 4;
		if (number[0] == '0' && zero_flag==0) {
			zero_flag = 1;
		}
		if (zero_flag == 1 && number[0] != '0') {
			result.push_back(nums[0]);
			zero_flag = 0;
		}
		if (zero_flag == 0) {
			result.push_back(nums[number[0] - '0']);
			if (unit[i - 1] !="") result.push_back(unit[i - 1]);
		}
		number.erase(number.begin());
		i--;
		if (i == 0) {
			if (group == 3) result.push_back(unit[5]);
			if (group == 2) result.push_back(unit[4]);
			group--;
		}
	}
	for (int i = 0; i < result.size(); i++) {
		cout << result[i];
		if (i != result.size() - 1) cout << " ";
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45681165/article/details/121636146