招银网络:笔试题(20190906)

本文介绍了如何使用C++编程语言实现黄金数的计算方法,通过遍历因子并比较乘积来找出符合条件的黄金数。此外,还展示了如何通过指针操作实现两个字符串的交换,避免了直接修改指针变量的问题。

黄金数的个数

设置一个临时变量来存放所有因子之积,当大于当前值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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值