Cracking The Coding Interview 5.7
2014-04-18 14:30
246 查看
//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
- Cracking the coding interview--Q1.4
- Cracking The Coding Interview 4.7_暂存
- Cracking the coding interview--Q20.1
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q3.4
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- Cracking The Coding Interview
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目5
- Cracking the coding interview--Q20.8
- 《Cracking the Coding Interview》——第13章:C和C++——题目7
- Cracking the coding interview--Q20.11
- 《Cracking the Coding Interview》——第17章:普通题——题目5
- 《Cracking the Coding Interview》——第18章:难题——题目2
- Cracking the Coding Interview 150题(二)
- Cracking The Coding Interview 3rd -- 00
- Cracking the Coding Interview
- Cracking the coding interview--Q12.4
- Cracking the coding interview–Q1.3
- Cracking the coding interview--Q1.4