1042 字符统计 (20分)
需要注意的是,如果直接输入cin>>a;会导致string a变成一个string数组,而不是单纯的字符串,所以需要使用getline(在string的头文件里,需要添加)
#include<iostream>
#include<string>
using namespace std;int main()
{string a;int b[123] = { 0 },max=0;char c='A';getline(cin, a);//不能使用cin,因为有空格for (int i = 0; i < a.size(); i++){if (a[i] >= 'A' && a[i] <= 'Z')b[(int)(a[i] + 'a'-'A')]++;//大写转小写存入if (a[i] >= 'a' && a[i] <= 'z')b[(int)a[i]]++;//小写直接存入}for (int i = 97; i < 123; i++){if (b[i] > max){max = b[i];//存最大个数,和字母c = i;}}cout << c << " " << max;return 0;
}
1043 输出PATest (20分)
#include<iostream>
#include<string>
using namespace std;int main()
{string a;int b[6] = { 0 };getline(cin, a);for (int i = 0; i < a.size(); i++){if (a[i] == 'P')b[0]++;if (a[i] == 'A')b[1]++;if (a[i] == 'T')b[2]++;if (a[i] == 'e')b[3]++;if (a[i] == 's')b[4]++;if (a[i] == 't')b[5]++;}while (b[0] != 0 || b[1] != 0 || b[2] != 0 || b[3] != 0 || b[4] != 0 || b[5] != 0){if (b[0] != 0) { cout << "P"; b[0]--; }if (b[1] != 0) { cout << "A"; b[1]--; }if (b[2] != 0) { cout << "T"; b[2]--; }if (b[3] != 0) { cout << "e"; b[3]--; }if (b[4] != 0) { cout << "s"; b[4]--; }if (b[5] != 0) { cout << "t"; b[5]--; }}return 0;
}
1044 火星数字 (20分)
一个复杂一些的题目,需要注意如果测试点2,4同时出错,是因为输入13整数倍时多输出了一个火星文的0
正确输出应该是:
对应代码段:
else//十位if(di!=0)//如果输入的是13的整数倍不需要输出低位数v.push_back(b[gao - 1] + " " + a[di]);elsev.push_back(b[gao - 1]);
完整代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;int main()
{int all = 0;cin >> all;string a[13] = { "tret", "jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec" };string b[12] = { "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou" };vector<string> v;getchar();//防止输入的第一个回车被当做输入!for (int i = 0; i < all; i++){string temp;getline(cin, temp);if (temp[0] >= '0' && temp[0] <= '9')//数字转火星文{int temp1 = stoi(temp);int di = 0, gao = 0;gao = temp1 / 13;di = temp1 % 13;if (gao == 0)//个位v.push_back(a[di]);else//十位if(di!=0)//如果输入的是13的整数倍不需要输出低位数v.push_back(b[gao - 1] + " " + a[di]);elsev.push_back(b[gao - 1]);}else//火星文转数字{if (temp.size() == 3)//个位{int flag = 100;//可能存在输入为一个高位,所以需要考虑两种情况for (int i = 0; i < 13; i++)if (a[i] == temp)flag = i;for (int i = 0; i < 12; i++)if (b[i] == temp)flag = (i+1)*13;v.push_back(to_string(flag));}else//十位{string b1 = temp.substr(0, 3);//获取十位string a1 = temp.substr(4, 3);//获取个位int temp1 = 0;for (int i = 0; i < 12; i++)if (b1 == b[i])temp1 += (i + 1) * 13;for (int i = 0; i < 13; i++)if (a1 == a[i])temp1 += i;v.push_back(to_string(temp1));}}}for (int i = 0; i < v.size(); i++)cout << v[i] << endl;return 0;
}