1. 程式人生 > >1082 Read Number in Chinese(字串處理)

1082 Read Number in Chinese(字串處理)

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
分析

本題的難點在於如何處理零,自己的程式碼在處理零時總存在測試點通不過,參考部落格1,現在對部落格的解法做一點個人的理解分析。解法使用zero標記是否在下一次碰到非零元素時是否輸出合理的零(i.e.連續0或者單獨一個0,按照中文讀法輸出一個ling),當zero=false時表示還未遇見0或者上次的0事件(i.e.連續0或者單獨0)已經處理完畢,當zero=true時,下次遇到非零元素時需要處理0,即先輸出ling再輸出非零元素的中文讀法,或者一直到最後一位(個位)依然未出現0元素,則不輸出ling,zero=true在本次標記中無效。

#include <iostream>
#include <algorithm>
#include<vector>
#include<cmath>
using namespace std;
string kv[]= {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
string bit[]= {"","Shi","Bai","Qian"};
string bit2[]= {"Yi","Wan",""};
int main() {
	int n;
	cin>>n;
	if(n==0) {
		cout<<"ling";
		return 0;
	}
	if(n<0) {
		cout<<"Fu ";
		n=-n;
	}
	int part[3];
	part[0]=n/100000000,part[1]=(n-n/100000000*100000000)/10000,part[2]=n%10000;
	bool zero=false;
	int printCnt=0;
	for(int i=0; i<3; i++) {
		int tmp=part[i];
		for(int j=3; j>=0; j--) {
			int curPos=8-i*4+j;
			if(curPos>=9)  continue;
			int cur=(tmp/(int)pow(10,j))%10;
			if(cur!=0) {
				if(zero) {
					cout<<" ling";
					zero=false;
				}
				if(j==0) {
					printCnt++==0?cout<<kv[cur]:cout<<" "<<kv[cur];
				} else {
					printCnt++==0?cout<<kv[cur]<<" "<<bit[j]:cout<<" "<<kv[cur]<<" "<<bit[j];
				}
			} else {
				if(!zero&&j!=0&&n/pow(10,curPos)>=10) zero=true;
			}
		}
		if(i!=2&&part[i]>0) cout<<" "<<bit2[i];
	}
	return 0;
}