Skip to content

Bit Magic

Avinash Kumar edited this page Nov 25, 2018 · 3 revisions
  1. http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
  2. https://www.geeksforgeeks.org/bits-manipulation-important-tactics/
  3. https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/tutorial/

Number of set bits -> while (x!=0) { x = x & (x-1)}

x-1 flips all the bits till (including) the rightmost set bit.


a+b = a^b + 2(a&b)


Swap two numbers -> a = a^b; b = b^a; a= a^b;


Flip the bits of number -> (Have number with all set bits) ^ number


This isn't strictly related to bit-magic but there are questions like conversion of string to integer where you need to figure out if your next digit is going to cause an overflow. There use this answer on stackoverflow (https://stackoverflow.com/a/13661672/648290). Pay special attention to the negative case. An implementation of this can be found at https://leetcode.com/problems/string-to-integer-atoi/

Clone this wiki locally