(doesn't include thinking hours)
This repository walks though on my implementation of swapping two variables without using a temporary variable or arithmetic operations or XOR.
- Initialize two variables,
a
andb
, with the values to be swapped. - Shift
a
to the left by the number of bits inb
. - Perform a bitwise OR between
a
andb
, storing the result inb
. - Perform a bitwise AND between
b
and a sequence of1
s matching the number of bits inb
, storing the result ina
. - Shift
b
to the right by the number of bits inb
. - Done!
Look at main.c
- Time complexity:
O(1)
- Space complexity:
O(1)
This code doesn't work for negative numbers as of now.
No limitations! Apart from the standard space issue same as with arithmetic operations.