Loading

1082 Read Number in Chinese (25 分)

1. 题目

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

2. 题意

给定一个不超过9位的整数,转化为用中文形式读出。例:123,中文读法为一百二十三,输出结果为yi Bai er Shi san;再如:-100800,中文读法为负一十万零八百,输出结果为Fu yi Shi Wan ling ba Bai

3. 思路

  1. 定义一个结果字符串res
  2. 如果输入整数为负数,则将Fu 加入到结果字符串中。
  3. 通过除10取余法取出整数的 每一位。
  4. 从整数高位开始遍历整数的每一位:如果有连续零出现,那么只有在当前位不为0,当前位的高一位为0时,才将ling加入结果字符串,其余时候ling均不加入结果字符串;当当前位不为0时,只要按照位数位置,将该位数字中文形式和该位置的念法加入结果字符串即可。

4. 代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// digit to string
string dtos(int digit)
{
	switch (digit)
	{
		case 1: return "yi";
		case 2: return "er";
		case 3: return "san";
		case 4: return "si";
		case 5: return "wu";
		case 6: return "liu";
		case 7: return "qi";
		case 8: return "ba";
		case 9: return "jiu";
		case 0: return "ling";
	}
	return "";
}

// shi bai qian to string 十百千转中文字符串 
string ctos(int cnt)
{
	switch (cnt)
	{
		case 1: return " Shi";
		case 2: return " Bai";
		case 3: return " Qian";
	}
	return "";
}

int main()
{
	int n;
	cin >> n;
	if (n < 0)
	{
		cout << "Fu ";
		n = -n;
	}
	vector<int> digits;
	// 除10取余法,取出给定整数的每一位 
	while (n)
	{
		int t = n % 10;
		digits.push_back(t);
		n /= 10;
	}
	int len = digits.size();
	if (len == 0) 
	{
		cout << "ling" << endl;
		return 0;
	}
	// 将最高位中文形式和“十百千”之一加入结果字符串 
	string res = dtos(digits[len - 1]) + ctos((len - 1) % 4);
	// 如果刚好最高为处于 万 或 亿 交界处,则将 万 或 亿 加入结果字符串 
	if (len - 1 == 4) res += " Wan";
	else if (len - 1 == 8) res += " Yi";
	// 从数字高位开始转化 
	for (int i = len - 2; i >= 0; --i)
	{
		// 如果当前位不为0,高位为0,将ling加入结果字符串 
		if (digits[i] != 0 && digits[i + 1] == 0) res += " " + dtos(0);
		// 如果当前位不为0,则将当前位中文形式和“十百千”之一加入结果字符串 
		if (digits[i] != 0) res += " " + dtos(digits[i]) + ctos(i % 4);
		// 当遍历到万和亿交界处时,将万或亿加入字符串 
		if (i == 4) res += " Wan";
		else if (i == 8) res += " Yi";
	}
	cout << res << endl;
	return 0;
}
 

posted @ 2021-10-30 12:02  August_丶  阅读(55)  评论(0编辑  收藏  举报