1、字符串最后一个单词的长度
#include <iostream>
using namespace std;
int main()
{
string str;
getline(cin, str);
int len = 0;
for(int i = str.size()-1; i>=0 && str[i] != ' '; --i)
{
++len;
}
cout << len << endl;
return 0;
}
2、计算字符个数
#include <iostream>
using namespace std;
int main()
{
string str;
getline(cin, str);
char c;
cin >> c;
int num = 0;
for(int i = 0; i < str.size(); ++i)
{
if(str[i] == c || str[i] == c + 32 || str[i] == c - 32)
{
num++;
}
}
cout << num << endl;
return 0;
}
3、明明的随机数
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
int num;
while(cin >> num)
{
unordered_map<int, int> hash;
while(num--)
{
int n;
cin >> n;
hash[n] = 1;
}
for(int i = 0; i < hash.size(); ++i)
{
if(hash[i] == 1)
{
cout << i << endl;
}
}
}
return 0;
}
4、字符串分隔
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin >> str)
{
while(str.size() > 8)
{
cout << str.substr(0, 8) << endl;
str = str.substr(8);
}
cout << str.append(8-str.size(), '0') << endl;
}
return 0;
}
5、进制转换
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin >> str)
{
int n = 0;
for(int i = 2; i < str.size(); ++i)
{
if(str[i] >= '0' && str[i] <= '9')
{
n = n * 16 + str[i] - '0';
}
if(str[i] >= 'A' && str[i] <= 'F')
{
n = n * 16 + str[i] - 'A' + 10;
}
}
cout << n << endl;
}
return 0;
}
6、质数因子
#include <iostream>
using namespace std;
int main()
{
long n;
cin >> n;
for(int i = 2; i <= n; ++i)
{
while(n % i == 0)
{
cout << i << ' ';
n /= i;
}
}
cout << endl;
return 0;
}
7、取近似值
#include <iostream>
using namespace std;
int main()
{
double n;
cin >> n;
int a = 0;
a = (int) n;
int b = (n - a) * 10;
if(b >= 5)
{
cout << a + 1 << endl;
}
else
{
cout << a << endl;
}
return 0;
}
8、合并表记录
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int num;
while(cin >> num)
{
unordered_map<int, int> hash;
vector<int> k;
while(num--)
{
int index;
int value;
cin >> index >> value;
k.push_back(index);
hash[index] += value;
}
sort(k.begin(), k.end());
k.erase(unique(k.begin(), k.end()), k.end());
for(auto i : k)
{
cout << i << ' ' << hash[i] << endl;
}
}
return 0;
}
9、提取不重复的整数
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
int n;
cin >> n;
int res = 0;
unordered_map<int, int> hash;
while(n)
{
if(hash[n % 10] == 0)
{
hash[n % 10] = 1;
res = res * 10 + n % 10;
}
n /= 10;
}
cout << res << endl;
return 0;
}
10、字符个数统计
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
string str;
getline(cin, str);
unordered_map<char, int> hash;
int num = 0;
for(int i = 0; i < str.size(); ++i)
{
if(hash[str[i]] == 0)
{
hash[str[i]] = 1;
num++;
}
}
cout << num << endl;
return 0;
}