Swap bits of 64-bit unsigned integer

12 August 2015

In order to swap two bits at given position (i,j) we have to perform two operations:

  • Compare two bits at indicies (i,j) if they differ
  • Toggle values at indicies (i,j) if bits differ.

The above algorithm is of O(1) complexity.

The following function will do the work:

func swapbits(n uint64, i uint, j uint) uint64 {
    if n>>i&1 != n>>j&1 {
        n ^= (1 << i) | (1 << j)
    return n

Find code samples here github.com/CodingBerg/golang-interview.

By one coder