You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This code does not work properly when x contains most significant bit set to 1, e.g. 0xFFFFFFFF.
Maybe this solution might avoid this problem:
Main idea is to shift right and add 0x1 to set bit
Save if (x == 0) to return 0 in this case: unsigned add_bit = (x == 0);
After setting all right bits to 1, shift right: x >>= 1;
Add bit: return (x + add_bit);
So the code will look like this: int leftmost_one(unsigned x) { unsigned add_bit = (x != 0); x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); x >>= 1; return (x + add_bit); // Add 1 if x != 0, 0 otherwise }
Thanks!
The text was updated successfully, but these errors were encountered:
This code does not work properly when x contains most significant bit set to 1, e.g.
0xFFFFFFFF
.Maybe this solution might avoid this problem:
0x1
to set bit(x == 0)
to return 0 in this case:unsigned add_bit = (x == 0);
x >>= 1;
return (x + add_bit);
So the code will look like this:
int leftmost_one(unsigned x)
{
unsigned add_bit = (x != 0);
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
x >>= 1;
return (x + add_bit); // Add 1 if x != 0, 0 otherwise
}
Thanks!
The text was updated successfully, but these errors were encountered: