Tuesday, July 11, 2017

Swap bits at position i and j in given number


public class SwapBits {
    /*
        Problem: Swap bits at position i and j in given number.
         Ex. swap(85,0,3). 85 looks like this in binary 1010101 swapping will convert it to 1011100
         Solution: Basic idea is simple first check the bits i and j if they are actually different
         if not we dont need to swap anything
         If the two bits are actually different create a bit mask with i and jth bit set to 1 and
         xor it with number which takes care of flipping those 2 bits
     */
    public long swapBits(long x, int i, int j){
        // First the value of firstBit and secondBit
        long firstBit = x >>> i & 1;
        long secondBit = x >>> j & 1;

        if(firstBit!=secondBit){
            //If the ith and jth bit are different then create bit mask with ith and jth bit set to 1
            long bitMask = (1L << i ) | (1L <<j);
            //xoring it with original number will switch ith and jth bit
            x = x ^ bitMask;
        }
        return x;
    }
}

No comments:

Post a Comment