Given an integer x and two bit indices i and j (0-based, LSB is index 0), swap the bits at positions i and j and return the resulting integer. Perform the swap only when the bits differ; if they are equal the integer remains unchanged.
If the bits at i and j differ, flipping both bits (XOR with a mask that has ones at i and j) effectively swaps them. If they are the same, no change is needed.
classSolution {
publicintswapBits(int x, int i, int j) {
int bi = (x >> i) & 1;
int bj = (x >> j) & 1;
if (bi != bj) {
int mask = (1 << i) | (1 << j);
return x ^ mask;
}
return x;
}
}
1
2
3
4
5
6
7
8
classSolution:
defswap_bits(self, x: int, i: int, j: int) -> int:
bi = (x >> i) &1 bj = (x >> j) &1if bi != bj:
mask = (1<< i) | (1<< j)
return x ^ mask
return x
classSolution {
publicintswapBitsExplicit(int x, int i, int j) {
int bi = (x >> i) & 1;
int bj = (x >> j) & 1;
if (bi == bj) return x;
int cleared = x &~((1 << i) | (1 << j));
int res = cleared | (bj << i) | (bi << j);
return res;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defswap_bits_explicit(self, x: int, i: int, j: int) -> int:
bi = (x >> i) &1 bj = (x >> j) &1if bi == bj:
return x
cleared = x &~(((1<< i) | (1<< j)))
res = cleared | (bj << i) | (bi << j)
return res