Bit Manipulation
Bitwise NOT
~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:
is equivalent to
Set the i
th bit
i
th bitUnset the i
th bit
i
th bitToggle the i
th bit
i
th bitCheck if i
th bit is set
i
th bit is setSet the i
th bit with x
i
th 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
n
is power of 2Traverse all the subsets
Complement of a subset
Traverse subsets of a set mask
mask
Sample output:
Or the other direction:
Sample output:
Given N
elements, traverse subsets of size K
(Gosper's Hack)
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 1
s, there are 2^K
subsets of it.
For N
elements, there are C(N, K)
subsets with K
bits of 1
s.
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
arraylogs[n]
is floor(log2(n))
.
Reference
Last updated