Problem Statement
Given a non-negative integer n
and two bits positions i
and j
, swap the ith and jth bits in the binary representation of n
. Bit positions are 0-indexed from the right (LSB)
Examples
Example 1:
Input: n = 28, i = 0, j = 3
Binary Representation of 28 = 11100
+-----+-----+-----+-----+-----+
| 1 | 1 | 1 | 0 | 0 |
+-----+-----+-----+-----+-----+
4 3 2 1 0
Swap bits at positions 0 and 3 -> 11100 -> 10101
After swapping:
+-----+-----+-----+-----+-----+
| 1 | 0 | 1 | 0 | 1 |
+-----+-----+-----+-----+-----+
4 3 2 1 0
Example 2:
Input: n = 73, i = 1, j = 6
Binary Representation of 73 = 1001001
+-----+-----+-----+-----+-----+-----+-----+
| 1 | 0 | 0 | 1 | 0 | 0 | 1 |
+-----+-----+-----+-----+-----+-----+-----+
6 5 4 3 2 1 0
Swap bits at positions 1 and 6 -> 1001001 -> 0001011
Output: 11
Different Approaches
1️⃣ Bitwise XOR Trick
Intuition:
- Get bit at position
i
:(n >> i) & 1
- Get bit at position
j
:(n >> j) & 1
- If they are different:
- Flip both bits using XOR:
n ^= (1 << i) | (1 << j)
- Flip both bits using XOR:
Dry Run:
For n = 28 (11100)
and i = 0, j = 3
- Bit at 0:
0
- Bit at 3:
1
- Since they differ → toggle both:
n ^= ( 1 << 0) | (1 << 3)
→10101
=21
Code:
#include <iostream>
using namespace std;
int swapBits(int n, int i, int j) {
// Check if the bits are different
int ith = (n >> i) & 1;
int jth = (n >> j) & 1;
if (ith != jth) {
// Toggle both bits
n ^= (1 << i);
n ^= (1 << j);
}
return n;
}
int main() {
int n = 28, i = 0, j = 3;
cout << "Original number: " << n << "\n";
cout << "After swapping bits: " << swapBits(n, i, j) << "\n";
return 0;
}
Complexity Analysis:
- Time Complexity:
O(1)
- Space Complexity:
O(1)