PATA.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

作者: CHEN, Yue

扫描二维码关注公众号,回复: 2998907 查看本文章

单位: PAT联盟

时间限制: 400ms

内存限制: 64MB

代码长度限制: 16KB

好菜啊,没想出来这个题怎么写,卡在不知道怎么简洁的输出“Yi”,“Wan”这些表示数量的单词上

 看了一下题解,因为最多只有9位数,所以可以把整个数字分为三节(如果有的话):个位段(1~4位),万位段(5~8位),亿位段(第9位),针对每一段进行处理,从最高位开始。

我们设两个指针left和right,left指向字符串首位,right指向末位,按段处理数据

AC代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
	string num[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
	string numstr[5]={"Shi","Bai","Qian","Wan","Yi"};
	string str;
	cin>>str;
	int len=str.length();
	int left=0,right=len-1;//left和right分别指向字符串首尾元素 
	if(str[0]=='-')
	{
		cout<<"Fu";
		left++;
	}
	while(left+4<=right)
		right-=4;
	//cout<<"left= "<<left<<endl;
	//cout<<"right= "<<right<<endl; 
	while(left<len)
	{
		bool flag=false;
		bool isprint=false;
		while(left<=right)
		{
			if(left>0&&str[left]=='0')//如果有连续的0就会一直执行 
				flag=true;
			else//遇到不为0的数 
			{
				if(flag==true)//存在累积的0 
				{
					cout<<" ling";
					flag=false;
				}
				//非首位后面每一位要多输出一个空格
				if(left>0)
				cout<<" ";
				cout<<num[str[left]-'0'];
				isprint=true;
				if(left!=right)//输出十百千位
					cout<<" "<<numstr[right-left-1];//仔细体会right-left-1
			}
			left++;//left右移一位
		}
		if(isprint==true&&right!=len-1)//不是个位就输出万或亿
			cout<<" "<<numstr[(len-1-right)/4+2];
			//right距离末尾的距离只有0,4,8三种可能
			//right!=len-1排除了1~5位数的情况(距离为0) 
		right+=4;//右移4位,输出下一节
	}
	return 0;
}

//本题最多9位数,也就是最大的数是x亿
//我们可以把整个数字划分为个节,万节,亿节
//我们从最高位的亿节开始输出,依次到万节,个节

猜你喜欢

转载自blog.csdn.net/qq_33657357/article/details/81211131