It is generally asked in interviews to check if a number can be converted into 2's power or not.
For e.g
8= 2^3
16=2^4
and so on...
Now if we solve this program without bit manipulation operators,
It will be difficult to solve it.
Hint:
IF a number is of 2's power, then its binary representation will have only one 1.
e.g 16= 10000
8 = 1000
and you may check for any number.
Now the problem is, how to implement this logic.
let say our number is 16,
then
binary of 16= 10000
and
binary of 15= 01111
16 & 15 = 00000
This result is only possible when number is of 2's power.
So generalized concept is
x = number & (number-1)
if(x==0)
{
printf("number is of 2's power");
}
else
{
printf("Tata bye bye.");
}
Cheers !!!!
0 comments: