360校园招聘

题目:



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

1 10 11

100 101 110 111

1000 1001 1010 1011 1100 1101 1110 1111


代码:

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<sstream>
#include<fstream>
#include<cstring>
#include<iomanip>
#include<stack>
#include<algorithm>
using namespace std;

int count_num(int num,set<int>&data){
	int count = 0;
	for (set<int>::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;
	set<int>data;
	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<int>::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<iostream>
#include<vector>
#include<map>
#include<set>
#include<sstream>
#include<fstream>
#include<cstring>
#include<iomanip>
#include<stack>
#include<algorithm>
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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值