题目:
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、对于特殊情况0和x亿进行直接的输出,其他的情况按照每四位一划分进行处理(即1-4,5-8,9),因为数字不超过9个digits位,故对于以亿为单位的数字只考虑个位的情况。
2、对于“ling”的输出,如100800中需要输出“ling”,设置标志位zero为全局变量,其含义为:前一位是否为0,在每次碰到不为0的数字时进行检查,若前一位为0,才输出“ling”,同时置zero为false,进行后面的处理,如3000在碰到一个0时不会马上输出,而是进行后面的判断,它在后面没有碰到非0数,最后结束输出。
3、对于空格的输出,用isFirst变量进行记录当前输出是否为第一位输出,对于第一位输出,输出 x,其他的输出为 空格+x。
4、分开的每四位处理,用Solve函数,处理时为了便于循环,将数字用sprintf函数转换为字符串进行遍历。
5、对于负数的输出,单独处理,若n < 0,输出“Fu”,将isFirst置为false,同时n = -n;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
string num[10] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
bool zero = false; //当读到零的时候不是马上输出,而是在读到下一个不为0的时候才输出0
//false代表没有先导零,true代表有前导零
bool isFirst = true; //对空格的判断,对第一个输出 x,其他输出 空格+x
void Solve(int n){
char s[6];
sprintf(s, "%d", n);
int len = strlen(s);
//对个十百千进行读
for(int i = 0; i < len; ++i){
if(s[i] != '0'){
if(zero){
printf(" ling");
zero = false;
}
if(isFirst){
isFirst = false;
}
else{
printf(" ");
}
cout << num[s[i] - '0'];
switch(len - i){
case 4: printf(" Qian"); break;
case 3: printf(" Bai"); break;
case 2: printf(" Shi"); break;
}
}
else{
zero = true;
}
}
}
void ReadNum(int n){
if(n < 0){
printf("Fu");
isFirst = false;
n = -n;
}
int temp;
//先处理亿上的问题,不超过十亿
temp = n / 100000000;
if(temp > 0){
//对于temp进行几亿的读取
if(!isFirst){
printf(" ");
}
cout << num[temp] << " " << "Yi";
isFirst = false;
}
//处理万上的问题
temp = n % 100000000 / 10000;
if(temp == 0){
if(n / 100000000){
zero = true;
}
}
else{
//对个十百千位上的数字处理
Solve(temp);
printf(" Wan");
}
//处理个十百千位
temp = n % 10000;
if(n != 0){
//对个十百千位上的数字处理
Solve(temp);
}
return;
}
int main(){
int n;
scanf("%d", &n);
if(n == 0){
printf("ling\n");
return 0;
}
else if(n % 100000000 == 0){
cout << num[n / 100000000];
printf(" Yi\n");
return 0;
}
ReadNum(n);
return 0;
}