![]() |
VOOZH | about |
Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.
Examples:
Input: n = 28, p1 = 0, p2 = 3
Output: 21
Explanation: 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 minimize your browser and try this yourself first.
Method 1:
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
Time Complexity: O(1)
Auxiliary Space: O(1)
Result = 21
Time Complexity: O(1)
Auxiliary Space: O(1)