团体程序设计天梯赛-练习集(五)

L1-023 输出GPLT (20分)

https://pintia.cn/problem-sets/994805046380707840/problems/994805113036587008

后面处理如何正确输出GPLT,且对应字母缺少则继续按顺序输出下一个存在的字母时不会处理,其实用一个while循环,里面嵌四个if判断语句即可。

 1 while(numG>0||numP>0||numL>0||numT>0)
 2     {
 3         if(numG>0)
 4         {
 5             cout<<"G";
 6             numG--;
 7         }
 8         if(numP>0)
 9         {
10             cout<<"P";
11             numP--;
12         }
13         if(numL>0)
14         {
15             cout<<"L";
16             numL--;
17         }
18         if(numT>0)
19         {
20             cout<<"T";
21             numT--;
22         }
23     }
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <string>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <iostream>
 7 using namespace std;
 8 int main()
 9 {
10     string str;
11     cin>>str;
12     int len=str.length();
13     int arr[5]={0};
14     int numG=0,numP=0,numL=0,numT=0;
15     for(int i=0;i<len;i++)
16     {
17         if(str[i]>='a'&&str[i]<='z') str[i]-=32;  //减32转换成大写
18         if(str[i]=='G') numG++; 
19         else if(str[i]=='P') numP++;
20         else if(str[i]=='L') numL++;
21         else if(str[i]=='T') numT++;
22     }
23     int sum=numP+numG+numL+numT;
24     while(numG>0||numP>0||numL>0||numT>0)
25     {
26         if(numG>0)
27         {
28             cout<<"G";
29             numG--;
30         }
31         if(numP>0)
32         {
33             cout<<"P";
34             numP--;
35         }
36         if(numL>0)
37         {
38             cout<<"L";
39             numL--;
40         }
41         if(numT>0)
42         {
43             cout<<"T";
44             numT--;
45         }
46     }
47     cout<<endl;
48     return 0;
49 }

猜你喜欢

转载自www.cnblogs.com/jianqiao123/p/12113266.html