![]() |
VOOZH | about |
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)
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:
7
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:
7
Related Article: