Include a snippet for swapping two variables using bitwise operators (#229)

This swaps the two values in the two variables without needing a third variable.
This commit is contained in:
Quan Yang
2021-10-02 02:33:25 -07:00
committed by GitHub
parent 99b0e687b0
commit 83e97337a6

View File

@ -18,6 +18,7 @@ Some helpful utility snippets:
- Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`. - Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
- Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`. - Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
- To check if a number is a power of 2, `(num & num - 1) == 0` or `(num & (-num)) == num`. - To check if a number is a power of 2, `(num & num - 1) == 0` or `(num & (-num)) == num`.
- Swapping two variables: `num1 ^= num2; num2 ^= num1; num1 ^= num2`
## Corner cases ## Corner cases