前几天参加完了一个实习生的机试和面试,分享几个题目,有的是我遇到的,有的是以前的。
本着交流的原则,我只是提供我的思路和解法,不一定是最优的,欢迎相互交流;
1.字符串判断,有且仅有首字母是大写。
输入:一串字符,有空格
输出:YES, NO
例如:Hello world! => YES Hello World! => NO
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
bool flag = false;
for (unsigned int i = 0; i < s.length(); i++)
if (s[i] >= 'A' && s[i] <= 'Z') {
flag = false;
break;
}
if (s[0] >= 'A' && s[0] <= 'Z') flag = true;
if (flag)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
2.两个数颠倒求和
输入:两个数字
输出:求和结果
例如:123 123 => 642 123 120 => 342
#include <iostream>
using namespace std;
int main() {
int a = 0, b = 0;
cin >> a >> b;
int sa = 0, sb = 0;
while (0 != a) {
int temp = a % 10;
a /= 10;
sa = sa * 10 + temp;
}
while (0 != b) {
int temp = b % 10;
b /= 10;
sb = sb * 10 + temp;
}
cout << sa + sb << endl;
return 0;
}
3.压缩字符串
输入:一串字符串,无空格
输出:压缩后字符串
例如:aaabbbcsdd => 3a3bcs2d asdvv => asd2v
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
int count = 0;
unsigned int i = 0;
for (i = 1; i < s.length(); i++) {
if (s[i] == s[i - 1]) {
count++;
continue;
} else if (0 == count) {
cout << s[i - 1];
} else {
cout << ++count << s[i - 1];
count = 0;
continue;
}
}
if (0 == count)
cout << s[i - 1] << endl;
else
cout << ++count << s[i - 1] << endl;
return 0;
}
目前先交流3道题目,以后有时间在继续。