Bitwise operators in interview questions
However scarce they are in production code, bitwise operators often surface in developer interview questions. Below is a quick selection of interview questions where the expected solution involves using bitwise operators.
Swap two numbers without using an intermediate variable
One common task that can be thrown upon you in an interview is, given two variables, swap their values without introducing a third variable.
This task can be solved quickly with 3 Bitwise OR operations, using the XOR swap algorithm. Here's the sequence of these operations:
SNIPPET
1x = x ^ y;
2y = x ^ y;
3x = x ^ y;
Let's try swap 2 and 5:
xxxxxxxxxx
let x = 2 // 0010
let y = 5 // 0101
x = x ^ y; // x is now 7 (0111), y is still 5 (0101)
y = x ^ y; // x is still 7 (0111), y is now 2 (0010),
x = x ^ y; // x becomes 5 (0101), y becomes 2 (0010)
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment