Post date: Jul 03, 2013 3:4:54 AM
Problem
Compute the ceiling power of 2
1 -> 1
2 -> 2
3 -> 4
4 -> 4
5 -> 8
6 -> 8
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Compute the ceiling power of 2
Created Date : 3-July-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
using namespace std;
int ComputeCeilingPower2(unsigned int x)
{
if((x & (x - 1)) == 0) return x;
x <<= 1;
while((x & (x - 1)) != 0){
x &= (x - 1);
}
return x;
}
int main(int argc, char* argv[])
{
for(int i = 0; i < 50; ++i){
cout << setw(4) << i;
cout << "-------->";
cout << setw(4) << ComputeCeilingPower2(i);
cout << endl;
}
return 0;
}
Output
0--------> 0
1--------> 1
2--------> 2
3--------> 4
4--------> 4
5--------> 8
6--------> 8
7--------> 8
8--------> 8
9--------> 16
10--------> 16
11--------> 16
12--------> 16
13--------> 16
14--------> 16
15--------> 16
16--------> 16
17--------> 32
18--------> 32
19--------> 32
20--------> 32
21--------> 32
22--------> 32
23--------> 32
24--------> 32
25--------> 32
26--------> 32
27--------> 32
28--------> 32
29--------> 32
30--------> 32
31--------> 32
32--------> 32
33--------> 64
34--------> 64
35--------> 64
36--------> 64
37--------> 64
38--------> 64
39--------> 64
40--------> 64
41--------> 64
42--------> 64
43--------> 64
44--------> 64
45--------> 64
46--------> 64
47--------> 64
48--------> 64
49--------> 64
Press any key to continue . . .