VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-bits-in-a-given-number/

⇱ Swap bits in a given number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap bits in a given number

Last Updated : 23 Jul, 2025

Given a number x and two positions (0 based from the right side) in the binary representation of x, write a function that swaps n bits at the given two positions and returns the result. It is also given that the two sets of bits do not overlap.

Examples:

Input:
x = 47 (00101111)
p1 = 1 (Start from the second bit from the right side)
p2 = 5 (Start from the 6th bit from the right side)
n = 3 (No of bits to be swapped)
Output:
227 (11100011)
Explanation:
The 3 bits starting from the second bit (from the right side) are
swapped with 3 bits starting from 6th position (from the right side)

Input:
x = 28 (11100)
p1 = 0 (Start from first bit from right side)
p2 = 3 (Start from 4th bit from right side)
n = 2 (No of bits to be swapped)
Output:
7 (00111)
Explanation:
The 2 bits starting from 0th position (from right side) are
swapped with 2 bits starting from 4th position (from right side)

Using XOR - O(1) time and O(1) space

We need to swap two sets of bits. XOR can be used in a similar way as it is used to swap 2 numbers using XOR.

The idea is to swap n bits at positions p1 and p2 in a number x by isolating these bit sets, XORing them to find the differences, and then selectively flipping only the bits that need to change, using the property that XOR marks differing bits and applying a second XOR operation restores the correct values in their swapped positions.

Step by step approach:

  1. Extract the first set of n bits from position p1 by right-shifting and masking with an n-bit mask
  2. Extract the second set of n bits from position p2 using the same technique
  3. XOR these two sets to identify which corresponding bits differ between them
  4. Position these XOR differences back at their original locations (p1 and p2)
  5. XOR the original number with these positioned differences to selectively flip only the bits that need to change

Output
7

Checking Each bit - O(1) time and O(1) space

The idea is to perform a bit-by-bit swap by iterating through each of the n positions, checking if the corresponding bits at the two positions differ, and if they do, flipping both bits to effectively swap their values - this approach handles the swap one bit at a time rather than operating on the entire bit sequences in a single operation.

Step by step approach:

  1. For each of the n positions, create masks to isolate individual bits at both locations.
  2. Check if the bits at the two positions are different (one is 0 and one is 1).
  3. If they differ, flip both bits by clearing the set bit and setting the unset bit.
  4. If the bits are identical (both 0 or both 1), no action is needed.
  5. Increment both position pointers and continue until all n bits are processed.

Output
7

Related Article:

Comment
Article Tags: