Bit Manipulation

Jim
1 min readJul 6, 2020

a few basic tricks:

  1. x & (-x) will only keep the rightmost 1 bit, the same for x & (~x + 1)
  2. x & (x-1) will clear/turn off the rightmost 1 bit
  3. given an array of integers, if every element appears twice except one, we can find that one integer by doing xor for all elements in that array.

these tricks are the fundamentals to solve more complex bit-manipulation problems like:

  • given an array of integers, if every elements appears twice except two numbers only appears once, find out these two numbers
  • given an array of integer, if every elements appears triple times except one elements only appears once, find out this number

--

--