mirror of
https://github.com/yangshun/tech-interview-handbook.git
synced 2025-07-28 12:43:12 +08:00
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:
@ -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
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user