PAT 解题报告 1082. Read Number in Chinese (25)

1082. Read Number in Chinese 题目描述:

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”. 用中文读出一串数字.

1082. Read Number in Chinese 算法分析:

顶多九位数, 最高一位也就是亿, 后面四位四位处理, 复杂的地方也就是对于零的处理, 注意两点: (1) 当前面没有任何输出的时候不要输出前置零, 比如344, 不要输出ling san Bai si Shi si (2) 注意后置零也不要输出, 比如100800, 处理800的时候看到第二个零的时候要做好输出比如807, ba Bai ling Qi的准备, 但是如果这个ling后面不再有非零位的时候比如800, 千万不要输出ba Bai ling这样子的东西, 可以AC的代码如下, 写的比较丑, 大家见谅.

#include <string>
#include <iostream>

std::string num[10] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
std::string wei[4]  = {"Qian","Bai","Shi", ""};

std::string gao(int digits[], bool &allZero, bool insertLing)
{
	allZero = true;
	std::string strResult("");
	std::string strBuffer("");
	for (int i = 0; i <= 3; ++i) {
		if (digits[i] == 0) {
			if (insertLing) {
				strBuffer = "ling";
				insertLing = false;
			}
		}
		else {
			if (strBuffer.size() > 0)
				strResult += (strBuffer + " " + num[digits[i]] + " " + wei[i] + " ");
			else
				strResult += (num[digits[i]] + " " + wei[i] + " ");

			allZero = false;
			insertLing = true;
			strBuffer = "";
		}
	}
	int len = strResult.size();
	while(len > 0 && strResult[len - 1] == ' ') len--;
	return strResult.substr(0, len);
}

int main()
{
	std::string input;
	std::cin >> input;

	if (input.empty()) {
		return -1; // incorrect
	}
	if (input.size() == 1 && '0' == input[0]) {
		std::cout << "ling" << std::endl;
		return 0;
	}

	int start = 0;
	int isBegining = true;
	bool needToInsertLing = false;
	if ('-' == input[0]) {
		std::cout << "Fu" ;
		start = 1;
		isBegining = false;
	}

	int digits[9];
	int ptr1 = 8;
	int ptr2 = input.size() - 1;
	for (; ptr2 >= start && ptr1 >= 0; --ptr2) {
		digits[ptr1--] = input[ptr2] - '0';
	}

	while (ptr1 >= 0) {
		digits[ptr1--] = 0;
	}
	if (digits[0] > 0) {
		if (isBegining) {
			std::cout << num[digits[0]];
			isBegining = false;
		}
		else
			std::cout << ' ' << num[digits[0]] << " Yi";
		needToInsertLing = true;
	}
	bool allZero = true;
	std::string strWanPart = gao(digits + 1, allZero, needToInsertLing);
	if (!allZero) {
		if (isBegining) {
			std::cout << strWanPart << " Wan";
			isBegining = false;
		}
		else
			std::cout << ' ' << strWanPart << " Wan";

		needToInsertLing = true;
	}
	std::string strOtherPart = gao(digits + 5, allZero, needToInsertLing);
	if (!allZero) {
		if (isBegining) {
			std::cout << strOtherPart;
			isBegining = false;
		}
		else
			std::cout << ' ' << strOtherPart;
	}
	return 0;
}

1082. Read Number in Chinese 注意点:

注意两点: (1) 当前面没有任何输出的时候不要输出前置零, 比如344, 不要输出ling san Bai si Shi si (2) 注意后置零也不要输出, 比如100800, 不要变成ba Bai ling之类的东西。

Written on July 16, 2014