360校园招聘

题目:

360校园招聘_第1张图片

360校园招聘_第2张图片

题目很简单,就是统计在1-n之间所有只由0和1构成的整数,例如

1 10 11

100 101 110 111

1000 1001 1010 1011 1100 1101 1110 1111


代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

int count_num(int num,set&data){
	int count = 0;
	for (set::iterator iter=data.begin(); iter!=data.end(); iter++){
		if (*iter<= num)count++;
	}
	return count;
}

int main(){
	ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
	int num;
	setdata;
	data.insert(1);
	data.insert(10);
	data.insert(11);
	int now = 11;
	int count = 2;
	while (now<=pow(10,9)){
		int base = pow(10, count);
		int size = data.size();
		data.insert(base);
		set::iterator iter = data.begin();
		while(size){
			data.insert(base+(*iter));
			iter++;
			size--;
		}
		count++;
		now = *(--data.end());
	}
	while (fin >> num){
		cout << count_num(num,data) << endl;
	}
	return 0;
}
编码的过程中可能要用到将数字转化成字符串,下面是一些可行的办法:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;


//方法1
int main(){
	ifstream fin("C:\\Users\\Dell\\Desktop\\data.txt");
	unsigned long long num;
	string str;
	stringstream mystream;
	while (fin>>num){
		mystream << num;
		mystream >> str;
		cout << str << endl;
		mystream.clear();
	}
	return 0;	
}

//方法2
int main(void)
{
	int number = 12345;
	char string[32];
	_itoa_s(number, string, 10);
	printf("integer = %d string = %s\n", number, string);
	return 0;
}



你可能感兴趣的:(算法)