HCL Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
There is a bug in the if-stmt. It works ok, if the bits are both set to 0, or if one is set to 1 and the other to 0. When they are both set to 1 though, it will mistakenly try to do a swap. Replace with:
! (((n & (1 << p)) >> p) ^ ((n & (1 << q)) >> q))
This explains it better, can be used for swapping block of bits :
graphics.stanford.edu/~seander/bithacks.html#SwappingBitsXOR
Swapping just two bits would be too simple as this can be done simply by checking if they are same or not. If not same then set 1 to 0 and 0 to 1 simply by xoring with ( 1<<position ).
Suppose positions are p and q and integer is n:
- Cerberuz April 14, 2013