Qualcomm Interview Question
Software Engineer / Developersif (( (n&(1<<i))>>i)^((n&(1<<j))>>j){
n^=(1<<i);
n^=(1<<j);
}
return n
If two bits are different, we just need to flip those two bits.
is'nt it true that in all the solutions above, if i and j are the given positions to be swapped, then we need to shift bits by i-1 and j-1 positions (eg: 1<<(i-1),etc)? correct me if i m wrong.
// swaps the ith bit and jth bit and returns swapped int
// assumes i=0 for the first bit from right
// and i-1 position for ith bit form right
int swap(const int &x, unsigned int i, unsigned int j)
{
// if the bits are same then return the same number
if ((int(1) & (x >> (i-1))) == ((int(1) & (x >> j-1))))
{
return x;
}
int ithBitSetToOne = (int(1) << (i-1));
int jthBitSetToOne = (int(1) << (j-1));
int bothIandJSetToOne = ithBitSetToOne | jthBitSetToOne;
return (x ^ bothIandJSetToOne)^int(0);
}
if ( (n&(1<<i))^(n&(1<<j)) ){
- Anonymous October 27, 2009n|~(1<<i);
n|~(1<<j);
}
return n