Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 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".

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

解答

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

string m1[] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
string m2[] = {"Qian", "Bai", "Shi"};
vector<string> ans;

void f(int x)
{
	char s[5]; sprintf(s, "%04d", x);
	for (int i = 0, start = 0; i < 4; i++)
	{
		if (s[i] == '0')
		{
			if (!start) continue;

			bool flag = 1;
			for (int j = i + 1; j < 4; j++) if (s[j] != '0') flag = 0;
			if (flag) return;

			if (s[i-1] != '0') ans.push_back("ling");
		}
		else
		{
			start = 1;
			ans.push_back(m1[s[i]-'0']);
			if (i < 3) ans.push_back(m2[i]);
		}
	}
}

int main()
{
	int n; scanf("%d", &n);

	if (n < 0) ans.push_back("Fu"), n = -n;

	int n1 = n / 100000000, n2 = n % 100000000 / 10000, n3 = n % 10000;
	if (n1)
	{
		f(n1);
		ans.push_back("Yi");	
	}
	if (n2)
	{
		if (n2 < 1000 && n1) ans.push_back("ling");
		f(n2);
		ans.push_back("Wan");
	}
	if (n3)
	{
		if (n3 < 1000 && (n1 || n2)) ans.push_back("ling");
		f(n3);
	}

	if (ans.empty()) printf("ling\n");
	else
	{
		printf("%s", ans[0].c_str());
		for (int i = 1; i < ans.size(); i++) printf(" %s", ans[i].c_str());
		printf("\n");
	}

	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论