Given an integer n and two bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from least significant bit (lsb). For example, the position for lsb is 0.
Input: n = 28, p1 = 0, p2 = 3 Output: 21 28 in binary is 11100. If we swap 0'th and 3rd digits, we get 10101 which is 21 in decimal. Input: n = 20, p1 = 2, p2 = 3 Output: 24
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to first find the bits, then use XOR based swapping concept, i..e., to swap two numbers ‘x’ and ‘y’, we do x = x ^ y, y = y ^ x and x = x ^ y.
Below is the implementation of the above idea
Result = 21
This question can be solved using left shift and XOR operators only. The idea is to set/unset the (p1)th bit and (p2)th bit by left-shifting 1 required number of times and using XOR operator to set/unset that bit (num = num ^ (1 << bit_position)).
Below is the implementation of the above code.
Output: Result = 21
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- How to swap two numbers without using a temporary variable?
- Check for Integer Overflow
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute the integer absolute value (abs) without branching
- Multiply a given Integer with 3.5
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Swap all odd and even bits
- Swap two nibbles in a byte
- Toggle all the bits of a number except k-th bit.
- Copy set bits in a range
- Print first n numbers with exactly two set bits
- Swap three variables without using temporary variable
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if a number has bits in alternate pattern | Set 1