What does the below function do ?
int lowbit(int x)
{
return x&(-x);
}
What does the below function do ?
int lowbit(int x)
{
return x&(-x);
}
why don’t you try taking some positive integers and see what does it do on notebook (dry run)?
Returns largest power of 2 dividing x
More info:
Thanks ,I tried that time but didn’t get any pattern but I understood this time
X&(-x) gives the ‘weight’ of the lowest non-zero bit in x.
-x is done by inverting all the bits in x and adding 1.
The weights are 1, 2, 4, 8, 16, etc…
Let’s do a few examples …
x=8 (binary: 00001000), x&(-x)=
00001000 & 11111000 => 8
x=7 (binary: 00000111), x&(-x)=
00000111 & 11111001 => 1
x=6 (binary: 00000110), x&(-x)=
00000110 & 11111010 => 2
x=57 (binary: 00111001), x&(-x)=
00111001 & 11000111 => 1
x=68 (binary: 01000100), x&(-x)=
01000100 & 10111100 => 4