您的位置:首页 > 其它

一个文件含有40亿个非负整数,使用1GB内存,找到一个不在该文件中的整数

2015-05-31 13:57 120 查看
#include <iostream>
#include <fstream>
using namespace std;

/*
使用位向量法解决
*/
void findNumber()
{
	long long numberOfInt = (long long)INT_MAX + 1;
	int len = (int)(numberOfInt / 32);
	int* array = new int[len];
	ifstream in("file.txt");
	if (!in)                    
	{
		cout << "file open error!" << endl;
		return;
	}	
	while (!in.eof())
	{
		int temp;
		in >> temp;            
		array[temp / 32] |= 1 << (temp % 32);	//计算元素在位数组的位置,然后把该位置1
	}
	for (int i = 0; i < len; i++)
	{
		for (int j = 0; j < 32; j++)
		{
			if (array[i] & (1 << j) == 0)	//扫描数组获得某一位为0,计算出不在文件中的数字
			{
				cout << i * 32 + j;
				return;
			}
		}
	}
}

int main()
{
	findNumber();
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: