Bit Mainpulatoin
Binary Number with Alternating Bits
Reverse Bits
Setting a bit
num |= 1 << x;clearing a bit
num &= ~(1<<x)toggling(flipping) a bit
num ^= 1 << xchecking a bit
bit = (num >> x) & 11 << i 就是Math.pow(2, i)
n & (-n)get the least significant standing bit,就是找最右边的1所代表的数,比如n = 6(110), n & (-n) = 2(10)n & (n - 1)效果为减去 n 的二进制表示中最右边为 1 的 bit,等效为n - n & (-n),n =6, n &(n-1) = 4n &(n - 1) == 0的话就说明n is power of 2n + (n & -n)就是直接在最低位的 1 上做进位加法如果是Unsigned Bit, 判断终止条件不能写
n > 0,而应该是N != 0,参见Number of 1 Bitsa^0 = a
a^a = 0
0b001100 ^0b101010 = 0b100110
所以可以in place swap(a, b)
a ^= b; b ^= a; a ^= b;Reverse Bits
Counting Bits
这题关键在于是Unsigned Bit,所以在while loop里的条件不能写n > 0,而应该是N != 0
Naive的想法就是找这32 bits里有多少个1,可以用
1 << i的技巧,这个方法有个好处就是可以算上最高位的1,不用care是否是Unsigned Bit还有一种就是用n -= n & (-n)的方法,或者n = n & (n - 1)。但是要注意是
while(n != 0)
Reverse Bits
拿到没做过的题目先想Brute Force,很多时候思路不见得不对
先shift bit,再赋值
FOLLOW UP: 如果多次call method如何优化?
We can divide an int into 4 bytes, and reverse each byte then combine into an int.
For each byte, we can use cache to improve performance.
给一个数num,要求返回0 <= i <= num的所有i包含bit 1的个数
这题可以用Fenwick Tree的思路做
当前数为i(假设是1010), 先找到i&(i - 1)的bit of 1的个数count[i&(i - 1)],可以发现count[i] = count[i&(i - 1)] + 1
这个想法真的很巧妙
given two numbers A and B, check how many different bits
一开始想到的是把32位都循环一遍,然后check最后一位,如果两个数的最后一位不一样就cnt++
上面这个方法虽然也过了,但显然没有get point
这题的核心其实是看C= A^B, get the number of bit 1 in C
Single number
每个数出现两次except for one, find that single one
XOR, a^a = 0
3 *n + 1个数,每个数出现3次except for one num,find it
把32 bits的每个bit位上求和sum, 如果sum % 3 != 0, 则说明res在此bit x上为 1
有两个数只出现一次,其余都出现2次
1 5 2 2 3 3 4 4
if XOR all nums. the res should be a^b, res != 0
二进制的某一位是1
意味着a和b在某一位上是不一样的
diff &= -diff;//get the right most "1" bit
把所有num分成两拨,一拨是第k位为0,另一拨是第k位为1
然后各自一拨single number I
Hamming Distance
Power of Two
利用n & (n-1) == 0性质
Power of Three
没法用bit manipulation
Power of Four
这题naive solution就是check num %4 == 0, num /=4, Time: O(logN)
还可以用bit manipulation, count bit i = i+2, num = 1 << i; Time: O(32)
Last updated
Was this helpful?