1、字符串最后一个单词的长度
#include
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
using namespace std;
int main()
{
string str;
char s;
getline(cin, str);
cin >> s;
int count = 0;
for(int i = 0; i < str.size(); ++i)
{
if(str[i] == s || str[i] == s+32 || str[i] == s-32)
count++;
}
cout << count << endl;
return 0;
}
3、明明的随机数
#include
#include
using namespace std;
int main()
{
int num;
int n;
while(cin >> num)
{
unordered_map<int, int> hash;
while(num--)
{
cin >> n;
hash[n] = 1;
}
for(int i = 0; i < hash.size(); i++)
{
if(hash[i] == 1)
cout << i << endl;
}
}
return 0;
}
4、字符串分隔
#include
using namespace std;
int main()
{
string str;
while(getline(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
using namespace std;
int main()
{
string str;
while(getline(cin, str))
{
if(str.size() < 0)
break;
//超出int范围
int num = 0;
for(int i = 2; i < str.size(); ++i)
{
if(str[i] >= '0' && str[i] <= '9')
{
num = num * 16 + str[i] - '0';
}
if(str[i] >= 'A' && str[i] <= 'F')
{
num = num *16 + str[i] - 'A' + 10;
}
}
cout << num << endl;
}
return 0;
}
6、质数因子
#include
using namespace std;
int main()
{
long n;
cin >> n;
//for循环从小到大输出质因子
for(int i = 2; i <= n; ++i)
{
while(n % i == 0)
{
cout << i << ' ';
n /= i;
}
}
cout << endl;
return 0;
}
7、取近似值
#include
using namespace std;
int main()
{
//浮点数尽量用double
double n;
cin >> n;
int a = (int)n;
int b = (n - a) * 10;
if(b >= 5)
cout << a+1 << endl;
else
cout << a << endl;
return 0;
}
8、合并表记录
#include
#include
#include
#include
using namespace std;
int main()
{
int num;
cin >> num;
unordered_map<int, int> hash;
vector<int> key;
while(num--)
{
int index, value;
cin >> index >> value;
key.push_back(index);//有重复的
hash[index] +=value;
}
//key去重
sort(key.begin(), key.end());
key.erase(unique(key.begin(), key.end()), key.end());
for(auto x : key)
cout << x << ' ' << hash[x] << endl;
/*
for(int i = 0; i < hash.size(); ++i)
{
if(hash[i] != 0)
cout << i << ' ' << hash[i] <
return 0;
}
9、提取不重复的整数
#include
#include
using namespace std;
int main()
{
int num;
int out;
cin >> num;
unordered_map<int, int> hash;
while(num)
{
if(hash[num % 10] == 0)
{
hash[num %10] = 1;
out = out * 10 + num % 10;
}
num /= 10;
}
cout << out << endl;
return 0;
}
10、字符个数统计
#include
#include
using namespace std;
int main()
{
int sum = 0;
char c;
unordered_map<char, int> hash;
while(cin >> c)
{
hash[c] = 1;
}
for(int i = 0; i < hash.size(); ++i)
{
//ascii 0 ''
if(hash[i] == 1)//if(hash[' ' + i] == 1)也是对的
sum++;
}
cout << sum << endl;
return 0;
}