题目描述:当输入一个数的时候:即输入:1,对应输出:一;输入:2,对应输出:二
当输入两个数的时候:即输入:12;输出:一十二;输入:10,输出:一十
当输入三位数的时候:即输入:123,输出:一百二十三;输入:100,输出:一百等等
这是完美世界的一道在线笔试题,当时时间不够,没能完全做完,想想真是遗憾,话不多说了直接上代码。
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <iostream>
5 #include <string.h>
6 using namespace std;
7 #define LEN 10
8 #define N 12
9
10 //将整数逆制--》即类是于:123变成321
11 int funtion(int value)
12 {
13 int tmp=0;
14 int res=0;
15 while(value !=0)
16 {
17 tmp=value%10;
18 res=res*10+tmp;
19 value/=10;
20 }
21 return res;
22 }
23 //处理只有一位数的时候
24 void case1_fun(int value,int *arr,char char_arr[N][LEN])
25 {
26 for(int i=0;i<LEN;++i)
27 {
28 if(value==arr[i])
29 cout<<char_arr[i];
30 }
31 }
32 //处理两位数的时候
33 void case2_fun(int value,int *arr,char char_arr[N][LEN],int count)
34 {
35 int tmp=0;
36 int k=0; //主要控制输出十的位
37 while(1)
38 {
39 for(int i=0; i<LEN; ++i)
40 {
41 tmp=value%10;
42 if(tmp==arr[i])
43 {
44 if(k==1)
45 cout<<char_arr[N-2]; //主要是输出十位 即十或者shi
46 if(tmp !=0) //主要防止个位不为零的时候
47 cout<<char_arr[i];
48 k++;
49 count--; //控制有多少位
50 value/=10;
51 if(value==0 && count==0)//必须要把两位数都得输出才结束
52 return;
53 }
54 }
55 }
56 }
57 //处理三位数的时候,这个要稍微麻烦一点
58 //这个特别注意的是不能将三位数分解成两位是和一位数去处理,主要是考虑整百的时候
59 //把高位的值取出来后就变成了零,零在这个函数中是不能被处理的
60 void case3_fun(int value,int *arr,char char_arr[N][LEN],int count)
61 {
62 //三位数的情景主要有三种格式:100,109,123 所以要考虑后两位为零和后一位为零的情况
63 int tmp=0;
64 int k=3; //控制百位和十位的输出
65 int v_tmp=0; //记录每一次模后的位数
66 while(1)
67 {
68 for(int i=0; i<LEN; ++i)
69 {
70 tmp=value%10;
71 if(tmp==arr[i])
72 {
73 if(k==2)
74 cout<<char_arr[N-1];
75 if(k==1 && v_tmp !=0)
76 cout<<char_arr[N-2];
77 if( tmp==0)
78 {
79 if(((value/10)%10)==0) //如果后两位都是零的话就不需要输出十位的十
80 NULL;
81 else//如果是一百零几的时候就需要输出中间这个零,否则就不需要输出中间隔零
82 cout<<char_arr[i];
83 }else
84 cout<<char_arr[i];
85 k--;
86 value/=10;
87 count--;
88 v_tmp=tmp;
89 if(value==0 && count==0)
90 return;
91 }
92 }
93 }
94 }
95 //
96 void fun(int value,int *arr,char char_arr[N][LEN])
97 {
98 if(value <=0 || value >=1000)
99 return;
100 int tmp=value;
101 int count=0;
102 int number=value;
103 while(number !=0)//主要记录有几位数
104 {
105 count++;
106 number/=10;
107 }
108 //用switch处理遇到的不同的情况,分开处理比较好
109 switch(count)
110 {
111 case 1:
112 case1_fun(tmp,arr,char_arr);
113 break;
114 case 2:
115 tmp=funtion(tmp);//得到了tmp这个数的逆值数据,下同
116 case2_fun(tmp,arr,char_arr,count);
117 break;
118 case 3:
119 tmp=funtion(tmp);
120 case3_fun(tmp,arr,char_arr,count);
121 break;
122 default:
123 break;
124 }
125 }
126
127 int main()
128 {
129 int value=0;
130 int arr[LEN]={0,1,2,3,4,5,6,7,8,9};
131//char char_arr[N][LEN]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu","shi","bai"};
132 char char_arr[N][LEN]={"零","一","二","三","四","五","六","七","八","九","十","佰"};
133 cout<<"please enter number :";
134 fflush(stdout);
135 // cin>>value;
136 while(cin>>value && value !=EOF)
137 {
138 fun(value,arr,char_arr);
139 fflush(stdout);
140 // cin>>value;
141 }
142 return 0;
143