1082 Read Number in Chinese (25分)【字符串处理】

1082 Read Number in Chinese (25分)

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<iostream>
#include<string>
using namespace std;

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

int main()
{
	string str;
	cin >> str;
	int len = str.length();
	int left = 0;
	int right = len - 1;
    if(str[0] == '-')
    {
        cout<<"Fu";
        left++;
    }
	while (left + 4 <= right)
	{
		right -= 4;
	}
	while (left < len)
	{
		bool flag = false;     //记录有没有积累的0
		bool isPrint = false;   //isPrint == false 表示当前部分没有输出过其中的位
		while (left <= right)
		{
			if (left > 0 && str[left] == '0')
				flag = true;
			else    //如果当前位不是0
			{
				if(flag == true)
				{
					cout << " ling";
					flag = false;
				}
				//只要不是首位(包括负号),后面的每一位前都输出空格
				if (left > 0)cout << " ";
				cout << num[str[left] - '0'];
				isPrint = true;
				if (left != right)
					cout << " " << wei[right - left - 1];
			}
			left++;
		}
		if (isPrint == true && right != len - 1)  //只要不是个位输出万亿
		{
			cout << " " << wei[(len - 1 - right)/4 + 2];
		}
		right += 4;
	}
	return 0;
}
发布了119 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lovecyr/article/details/104651100