Cracking The Coding Interview 5.7

//An array A[1…n] contains all the integers from 0 to n except for one number which is missing. In this problem, 
//we cannot access an entire integer in A with a single operation. The elements of A are represented in binary,
//and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time. Write code to find the missing integer. Can you do it in O(n) time?
//
//	
#include <iostream>
#include <vector>
using namespace std;

void print(int p)  
{
	vector<int> v;
	for (int k = 0;k<32; k++)  
	{  
		int t = p&1;  
		v.push_back(t);  
		p=p>>1;  
	}  
	for (int i = v.size()-1;i>-1; i--)  
	{  
		cout<<v[i]<<" ";  
	}  
	cout<<endl;
}

/***取得a[i]的j位***/
int fetch(int *a, int i,int j)
{
	int t = a[i];
	t = t>>j;
	return (t&1);
}


/***左移,相或,得到a[i]***/
int getai(int *a, int i)
{
	int t = 0;
	for (int s=31; s>-1; s--)
	{
		t = t<<1;
		t = t|fetch(a, i, s);
	}

	return t;
}


/***缺少的数为:(0+1+2+...n) - (a[0]+...a[n-1]) ***/
int getN(int *a,int n)
{
	int sumn = 0;
	int suma = 0;
	for (int i = 0;i <n; i++)
	{
		sumn += i;
		suma += a[i];
	}
	return sumn + n - suma;
}

int main()
{
	int a[] = {
		0, 1, 2, 3, 4, 5, 7, 8, 9, 10
	};
	cout<<getN(a,10);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值