//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;
}
Cracking The Coding Interview 5.7
最新推荐文章于 2014-04-28 23:23:07 发布