Bit Manipulation

Bitwise NOT

~val
NOT 0111 (decimal 7)
= 1000 (decimal 8)

~val is also equivalent to val != -1, since -1 is the only one number whose bitwise NOT is 0.

So if val is some non-negative number, the following:

for (int i = val; ~i; --i)

is equivalent to

for (int i = val; i >= 0; --i)

Set the ith bit

mask |= 1 << i

Unset the ith bit

mask &= ~(1 << i)

Toggle the ith bit

Check if ith bit is set

Set the ith bit with x

Get the lowest bit

Example:

Count bit 1s

Note that the pop in this function means population.

Count trailing zeros

Count leading zeros

Check if n is power of 2

Traverse all the subsets

Complement of a subset

Traverse subsets of a set mask

Sample output:

Or the other direction:

Sample output:

Given N elements, traverse subsets of size K (Gosper's Hack)

Traverse subsets of subsets

Given an array of N elements, traverse all its subsets. For each of the subsets, traverse its all non-empty subsets as well.

Note that the time complexity is O(3^N) instead of O(2^N * 2^N) = O(4^N).

Math proof:

For a subset mask with K bits of 1s, there are 2^K subsets of it.

For N elements, there are C(N, K) subsets with K bits of 1s.

So the total number is SUM( C(N, K) * 2^K | 0 <= K <= N ).

Since (1 + x)^N = C(N, 0) * x^0 + C(N, 1) * x^1 + ... + C(N, N) * x^N, let x = 2, we have 3^N = SUM( C(N, K) * 2^K | 0 <= K <= N ).

Intuitive proof:

For each bit index i (0 <= i < N), the i-th bits of mask and sub must be one of 11, 10, 00, and can't be 01. So each bit has 3 possibilities, the total complexity is O(3^N).

Calculate subset sums

Or

where lowbit(x) = x & -x, and __builtin_ctz(x) counts the trailing zeros in x. Since lowbit(mask) is a power of two, __builtin_ctz(lowbit(mask)) == log2(lowbit(mask)).

Generate logs array

logs[n] is floor(log2(n)).

Reference

Last updated

Was this helpful?