华为机试在线训练C++版(31~40)
31.【中级】单词倒排
之前有一个类似的题目,用的简单的方法:
#include <iostream>
#include <string>
using namespace std;
int main() {
string input, output;
while (cin >> input) {
output = input + ' ' + output;
}
cout << output << endl;
return 0;
}
然而并没有通过,所以还是老实的做吧:从前往后扫描字符串,遇到是单词就入vector,最后反向输出即可:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
vector<string>svec;
svec.clear();
string temp = "";
for (int i = 0; i < str.size(); ++i) {
if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
temp += str[i];
else {
if (temp.size() > 0) {
svec.push_back(temp);
temp = "";
}
}
}
if (temp.size() > 0) {
svec.push_back(temp);
}
for (int i = svec.size() - 1; i > 0; --i) {
cout << svec[i] << ' ';
}
cout << svec[0] << endl;
}
return 0;
}
32.字符串运用-密码截取
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
while (cin >> str) {
const int len = str.size();
if (len <= 1) return -1;
int maxLen = 0;
for (int i = 1; i < len; i++) {
//寻找以i-1,i为中点偶数长度的回文
int low = i - 1, high = i;
while (low >= 0 && high < len && str[low] == str[high]) {
low--; high++;
}
if (high - low - 1 > maxLen)
maxLen = high - low - 1;
//寻找以i为中心的奇数长度的回文
low = i - 1; high = i + 1;
while (low >= 0 && high < len && str[low] == str[high]) {
low--; high++;
}
if (high - low - 1 > maxLen)
maxLen = high - low - 1;
}
cout << maxLen << endl;
}
return 0;
}
33.整数与IP地址间的转换
#include <iostream>
using namespace std;
int main(){
long long n, a1, a2, a3, a4;//n代表输入的整形数字;四个数分别代表输入的ip地址
char ch;//代表输入的IP地址中的点
while(cin >> a1 >> ch >> a2 >> ch >> a3 >> ch >> a4){
cin >> n;
long long res = 0;
//采用左移运算符,把IP地址中的每一位依次向左移动24位(乘以2的24次方),16位,8位,0位。
res += (a1 << 24) + (a2 << 16) + (a3 << 8) + a4;
a1 = n >> 24;
//255的二进制码是11111111,这样就可以只保留最后8位的数字,而把前面的都变为000000000
a2 = (n >> 16) & 255;
a3 = (n >> 8) & 255;
a4 = n & 255;
cout << res << endl << a1 << '.' << a2 << '.' << a3 << '.' << a4 << endl;
}
return 0;
}