Bit Manipulation
Last updated
Was this helpful?
Last updated
Was this helpful?
这个帖子讲得非常好!
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 & ~(A - 1)
or x ^ (x & (x-1))
Remove last bit A & (A-1)
Get all 1-bits ~0
XOR 主要用来剔除掉偶数个的相同元素,而生下来单独存在的元素
特性:
(1) 恒等律:A ^ 0 = A
(2) 归零律: A ^ A = 0
相同的元素互相抵消;任何元素与 0 异或得到本身。
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.)
selecting certain bits
reverse the bits in integer
Keep as many 1-bits 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.