1. 题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
#include
#include
#include
using namespace std;
int Length_last_string(string &a)
{
int lengtn = a.size();
int resutl = 0;
for (int i = lengtn - 1; a[i] != ' '; i--)
{
resutl = resutl + 1;
if (i == 0)
{
resutl = lengtn;
break;
}
}
return resutl;
}
int main()
{
string a;
getline(cin, a);
cout << Length_last_string(a) << endl;
system("pause");
return 0;
}
2.题目描述
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作(同一个测试用例里可能会有多组数据,希望大家能正确处理)。
Input Param
n 输入随机数的个数
inputArray n个随机整数组成的数组
Return Value
OutputArray 输出处理后的随机整数
注:测试用例保证输入参数的正确性,答题者无需验证。测试用例不止一组。
#include
#include
#include
#include
using namespace std;
void Sort(vector &a,vector &b)
{
b.push_back(a[0]);
bool symbol;
for (unsigned int i = 1; i < a.size(); i++)
{
symbol = 0;
for (int j = 0; j < b.size(); j++)
{
if (a[i] == b[j])
{
symbol = 1;
break;
}
}
if (symbol == 0) b.push_back(a[i]);
}
sort(b.begin(), b.end());
}
int main()
{
int num;
vector array;
while(cin >> num)//必须采用while,因为是多组测试,不断用于测试
{
for (int i = 0; i < num; i++)
{
int temp;
cin >> temp;
array.push_back(temp);
}
vector result_array;
Sort(array, result_array);
for (unsigned int i = 0; i < result_array.size(); i++)
{
printf("%d\n",result_array[i]);
}
array.clear();//基于多组测试数据,因此,每次测完必须清除
result_array.clear();
}
system("pause");
return 0;
}
下面是一位大神解答,十分的巧妙,反过来想,1-1000的数类比于固定箱子,没有放进去时为0 ,放进去是为1
#include
using namespace std;
int main() {
int N, n;
while (cin >> N) {
int a[1001] = { 0 };
while (N--) {
cin >> n;
a[n] = 1;
}
for (int i = 0; i < 1001; i++)
if (a[i])
cout << i << endl;
}
return 0;
}//阿西吧
3.题目描述
求一个整数的质数因子,并且从小到大排序。
//质数因子_
void Prime_Factor(int a)
{
long temp = a;
vector temp1;
for (long i = 2; i <=a; i++)
{
while (temp % i == 0)
{
temp1.push_back(i);
temp = temp / i;
}
}
sort(temp1.begin(), temp1.end());
for (unsigned int i = 0; i < temp1.size(); i++)
{
cout << temp1[i]<
}
}