Bit Manipulation · Easy
Swap Two Bits at Given Positions
Solve it on DeVert Campus - free code runner
Problem
Given a non-negative integer N and two bit positions i and j (0-indexed from the least significant bit), swap the bits of N at positions i and j and print the resulting integer. If the bits at those positions are already equal (including when i equals j), the value is unchanged.
Input and output
Input: A single line containing three space-separated integers: N, i, and j.
Output: A single line containing N after swapping the bits at positions i and j.
Example
Input: 5 0 1 Output: 6
Constraints
0 <= N <= 2^31 - 1; 0 <= i, j <= 30
Key observation
When i equals j, the 'bits are equal' check (trivially true, comparing a position to itself) naturally leaves the number unchanged - a clean, automatic handling of this edge case without needing an explicit i==j check.
Intuition
Swap the values of two specific bit positions within a number.
Brute force: Convert the number to a string or array of individual bit characters, swap the two characters directly, and convert back - this works but is more roundabout than direct bitwise manipulation.
Optimised: Since flipping a bit that's DIFFERENT from its swap partner via XOR effectively exchanges the two values (a bit that becomes what its partner used to be), checking whether the bits differ FIRST (and skipping entirely if they're equal) avoids unnecessary work and correctly handles the i==j edge case for free.
Step by step
1. Extract the bit at each position using (N >> pos) & 1.
2. If the two bits are already EQUAL (including when i equals j), nothing needs to change.
3. If they DIFFER, flip BOTH positions using XOR: n ^= (1 << i); n ^= (1 << j) - flipping two differing bits swaps them.
Complexity
Time: O(1) - a constant number of bitwise operations.
Space: O(1) - no extra storage.
Edge cases
i equal to j always leaves N unchanged; N = 0 stays 0 regardless of i and j since every bit is 0.
Interview tip
Be ready to explain why checking equality FIRST (rather than always XOR-flipping both positions unconditionally) matters - unconditionally flipping EQUAL bits would actually flip them both to the SAME opposite value, not swap them, silently producing a wrong answer.