Amazon Interview Question
Software Engineer / DevelopersTry your function with 4, 8, 16, ...
you will get 8, 16, 32, ... which is wrong.
it should return 4, 8, 16, ...
int Ceiling2(int x){
if (x && !(x & x-1))
return x; //power of two
else{
y=x;
while(y & (y-1)){
// Removing the extra set bit.
y &= (y-1);
}
return y<<1;
}
}
@Anonymous You are wrong.
if 4,8,16...are given as input then output should be 8,16,32...
The question asks for "the next higher power of 2".
@Ankush Bindlish Gr8 soln
#include<stdio.h>
int roundOff(int number){
int maxBit = 0;
int mask = 1;
while(number != 0){
number >>= 1;
maxBit++;
}
mask <<= maxBit;
return mask;
}
int main(){
printf("%d\n",roundOff(1));
printf("%d\n",roundOff(2));
printf("%d\n",roundOff(3));
}
Ran is correct except that while loop should be less than [not less than or equal to]
int pow(int n){
int i=1;
while(i<n) // Change here instead of i<=n which makes it invalid for n = 2^k
i<<=1;
return i;
}
This can be one of teh solutions:
if ((x&(x-1)) == 0)
return x;
while(x&(j))
j = j+1;
return j;
- Ankush Bindlish January 02, 2010