On Sep 14, 10:27 pm, Gene <[email protected]> wrote:
> My solution just tests bit i and either sets or clears bit j based on
> the result.  Then it does the same testing bit j and setting or
> clearing bit i.
>
> There are many other possibilities.  It would be slick if C shift
> operators accepted negative shift values. But they don't.  Instead you
> could shift the bits down to position 0 then shift them back up to
> their swapped positions and substitute in the input value. This one
> has a spooky symmetry.
>
> unsigned swap(unsigned x, int i, int j)
> {
>   unsigned bit_i = (1u << i) & x;
>   unsigned bit_j = (1u << j) & x;
>   return (x ^ bit_i ^ bit_j) | (bit_i >> i << j) | (bit_j >> j << i);
>
> }
>

Sorry.  Just noticed this is roughly what Dave did except I used xor
to clear the bits at positions i and j.

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to