黄金数的个数
设置一个临时变量来存放所有因子之积,当大于当前值cu则可以直接中止。如果两者相等,则累加值count加一。
#include <iostream>
using namespace std;
int gold_number(int num)
{
if(num < 6)
return 0;
int count = 0;
for(int nu=6; nu <= num; nu++)
{
int current = 1;
for(int cu=2; cu < nu; cu++)
{
if(nu%cu == 0)
{
current *= cu;
}
if(current > cu)
break;
}
if(current == nu)
{
count += 1;
}
}
return count;
}
int main()
{
int num;
cin >> num;
int res;
res = gold_number(num);
cout << res << endl;
}
随机打乱一个有序序列
原题为一个编程填空题,有点搞不懂思路,也不明白迭代器和索引是提供两种方式还是都是有作用的,但是注意到了题目额外定义了一个idx,但是代码中却没有使用。所以,idx应该就是用来产生随机数的,而条件判断应该考虑到只有一个元素的情况避免死循环,同时要注意在vector中删除一个元素应该使用erase函数。
array.erase(array.begin()+idx);
:删除第idx个元素。
#include <iostream>
#include <vector>
#include <time.h>
#include <iterator>
using namespace std;
void shuffle(vector<int> array)
{
int i=0, idx;
vector<int>::iterator it;
srand((unsigned)time(NULL));
while(!array.empty())
{
idx = 0 + rand()%(array.size()); // 第一处
for(i=0, it=array.begin(); it != array.end(); it++, i++)
{
if(array[idx] != array[i] || array.size() == 1) // 第二处
{
cout << array[idx] << " ";
array.erase(array.begin()+idx); // 第三处
break;
}
}
}
cout << endl;
}
int main()
{
int num;
vector<int> seq;
while(cin >> num)
{
seq.push_back(num);
}
shuffle(seq);
return 0;
}
交换两个字符串
使用指针变量作为形参来操作,直接交换s和t指向的变量的值,而不是改变形参指针变量s和t的指向。要输入char*
类型的值,可采用以下方式:
-
char* s = new char[maxSize]; cin >> s;
-
char* s; string temp; cin>>temp; s = const_cast<char*>(temp);
#include <iostream>
#include <string>
using namespace std;
void swap(char* &s, char* &t);
int main()
{
char* s = new char[100];
char* t = new char[100];
cin >> s;
cin >> t;
swap(s, t);
cout << s << " " << t << endl;
return 0;
}
void swap(char* &s, char* &t)
{
char* temp = s;
s = t;
t = temp;
}