Wiki
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include lowlevel device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions. Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and bit shifts.
Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give manyfold speed ups, as bit manipulations are processed in parallel, but the code can become more difficult to write and maintain.
Details
Basics
At the heart of bit manipulation are the bitwise operators & (and),  (or), ~ (not) and ^ (exclusiveor, xor) and shift operators a << b and a >> b.
There is no boolean operator counterpart to bitwise exclusiveor, but there is a simple explanation. The exclusiveor operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusiveor, with the operator of a caret, ^, performs the exclusiveor operation on each pair of bits. Exclusiveor is commonly abbreviated XOR.
 Set union A  B
 Set intersection A & B
 Set subtraction A & ~B
 Set negation ALL_BITS ^ A or ~A
 Set bit A = 1 << bit
 Clear bit A &= ~(1 << bit)
 Test bit (A & 1 << bit) != 0
 Extract last bit A&A or A&~(A1) or x^(x&(x1))
 Remove last bit A&(A1)
 Get all 1bits ~0
Examples
Count the number of ones in the binary representation of the given number


Is power of four (actually mapchecking, iterative and recursive methods can do the same)


^
tricks
Use ^
to remove even exactly same numbers and save the odd, or save the distinct bits and remove the same.
Sum of Two Integers
Use ^
and &
to add two integers


Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. (Of course, you can do this by math.)



tricks
Keep as many 1bits as possible
Find the largest power of 2 (most significant bit in binary form), which is less than or equal to the given number N.


Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Solution




&
tricks
Just selecting certain bits
Reversing the bits in integer


Bitwise AND of Numbers Range
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4.
Solution


Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
Solution




Application
Repeated DNA Sequences
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: “ACGAATTCCG”. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10letterlong sequences (substrings) that occur more than once in a DNA molecule.
For example,
Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,
Return: [“AAAAACCCCC”, “CCCCCAAAAA”].
Solution


But the above solution can be invalid when repeated sequence appears too many times, in which case we should use
unordered_map<int, int> keyMap
to replacechar keyMap[1<<21]{0}
here.Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. (bitcounting as a usual way, but here we actually also can adopt sorting and Moore Voting Algorithm)
Solution
123456789101112 int majorityElement(vector<int>& nums) {int len = sizeof(int)*8, size = nums.size();int count = 0, mask = 1, ret = 0;for(int i = 0; i < len; ++i) {count = 0;for(int j = 0; j < size; ++j)if(mask & nums[j]) count++;if(count > size/2) ret = mask;mask <<= 1;}return ret;}
Single Number III
Given an array of integers, every element appears three times except for one. Find that single one. (Still this type can be solved by bitcounting easily.) But we are going to solve it by digital logic design
Solution


Maximum Product of Word Lengths
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”.Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.
Solution
Since we are going to use the length of the word very frequently and we are to compare the letters of two words checking whether they have some letters in common:
 using an array of int to prestore the length of each word reducing the frequently measuring process;
 since int has 4 bytes, a 32bit type, and there are only 26 different letters, so we can just use one bit to indicate the existence of the letter in a word.1234567891011121314int maxProduct(vector<string>& words) {vector<int> mask(words.size());vector<int> lens(words.size());for(int i = 0; i < words.size(); ++i) lens[i] = words[i].length();int result = 0;for (int i=0; i<words.size(); ++i) {for (char c : words[i])mask[i] = 1 << (c  'a');for (int j=0; j<i; ++j)if (!(mask[i] & mask[j]))result = max(result, lens[i]*lens[j]);}return result;}
Attention
 result after shifting left(or right) too much is undefined
 right shifting operations on negative values are undefined
 right operand in shifting should be nonnegative, otherwise the result is undefined
 The & and  operators have lower precedence than comparison operators
Sets
All the subsets
A big advantage of bit manipulation is that it is trivial to iterate over all the subsets of an Nelement set: every Nbit value represents some subset. Even better, if A is a subset of B then the number representing A is less than that representing B
, which is convenient for some dynamic programming solutions.
It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don’t mind visiting them in reverse order (if this is problematic, put them in a list as they’re generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just i = (i  1) & superset
.


Actually there are two more methods to handle this using recursion
and iteration
respectively.
Bitset
A bitset stores bits (elements with only two possible values: 0 or 1, true or false, …).
The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char).


Always welcom new ideas and practical
tricks, just leave them in the comments!