
// given a 64-bit number and two bit locations (in ints), swap the bit values in those positions. 
// NOTE: index 0 is LSB, 63 is MSB
// the bit swap will be necessary when the values are different

public class SwapBits {
    public static void main(String[] args) {
        swapBits(24L, 1, 2);
    }

    // swap bits in ith and jth locations of x and return resulting x
    public static long swapBits(long x, int i, int j) {
        // extract bits into array
        long[] bits = new long[64];
        int count = 0;
        long rem = x % 2;
        x = x / 2;
        bits[count] = rem;
        count++;

        while(x > 0) {
            rem = x % 2;
            x = x / 2;
            bits[count] = rem;
            count++;
        }

        // swap bits if required
        if(bits[i] != bits[j]) {
            long temp = bits[i];
            bits[i] = bits[j];
            bits[j] = temp;
        }

        // reconstruct & return
        long total = 0L;
        for(int k = 0; k < bits.length; k++) {
            total += bits[k] * Math.pow(2, i);
        }
        return total;
    }

    // print array representing binary number in string format
    public static String printBin(long[] x) {
        String n = "";
        for(int i = x.length-1; i >= 0; i--) {
            n = n + x[i];
        }
        
        return n;
    }
}

@@ -291,16 +291,45 @@
  1, 2);%0A
+        swapBits(1, 2, 24L);%0A
     %7D%0A%0A 
@@ -1126,24 +1126,544 @@
 tal;%0A    %7D%0A%0A
+    // swap bits using bitwise operations (O(1))%0A    public static long swapBits(int i, int j, long x) %7B%0A        // extract the ith and jth bits and check if they differ%0A        if(((x %3E%3E%3E i) & 1) != ((x %3E%3E%3E j) & 1)) %7B%0A            // bits differ - swap by flipping values%0A%0A            // select bits to flip w/ bitmask. Since x %5E 1 = 0 when x = 1 and 1%0A            // when x = 0, we can perform the flip XOR%0A            long bitMask = (1L %3C%3C i) %7C (1L %3C%3C j);%0A            x %5E= bitMask;%0A        %7D%0A%0A        return x;%0A    %7D%0A%0A
     // print

Update SwapBits