1. Count how many 1
in binary representation of a 32-bit integer a.
解法1:直观地计数a在32位上1的个数,count += a & (1<<i). notice,不要用a<<1,因为当a = -1时,a<<1结果还是 -1.
解法2: 每次a&(a-1), ∵ (a-1)会把a的最后一位为1的bit变成0,所以在a==0之前,该操作的个数就是1的个数。
2.Single number:在一个数组里,除了一个数,其他所有的数都出现了两次
解法:利用 a^a=0,a^0 = a的特性,把数字里面的所有数字在一起取异或,根据bit操作的可交换性,剩下的即为single number
3.Single number Ⅱ:在一个数组里,除了两个数,其他所有的数都出现了两次
解法:based on Ⅰ,所有数字异或结果是a^b,并且a != b,找出a^b里最末一个为0的bit x(可利用count 1的解法2), 说明在该 x bit上,a和b的bit不同,根据该bit可将数组分为两边,一边在x bit跟a相同,一边则跟b相同。再按Ⅰ来做,分别得到a, b.
4. Single number ⅡⅠ:在一个数组里,除了一个数,其他所有的数都出现了三次。
解法:hmm, a little based on ⅠⅠ. 思路就是,建立一个位数组 t = new int[32]. 然后对于里面每个bit,遍历数组,对1计数,满3就消0,最后的数组对应成int就是答案。
5. Add two numbers:
解法:First, we can use "and"("&") operation between a and b to find a carry.
carry = a & b, then carry = 0001
Second, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a,
Then, we shift carry one position left and assign it to b, b = 0010.
Iterate until there is no carry (or b == 0)
PS: 其实很多其他的题,如string类,可以转化成一个int来进行存储或者比较神马的,也许比较方便呢
PPS: 在进行bit operation时,如写&,^等combo进行if判断时,要注意适当加好括号,不然compile就说你=两边怎么又不一致了啊
PPPS:
"&" AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)
"^" XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)
"~" NOT operation, for example, ~2(0010) => -3 (1101) what??? Don't get frustrated here. It's called two's complement.
1111 is -1, in two's complement
1110 is -2, which is ~2 + 1, ~0010 => 1101, 1101 + 1 = 1110 => 2
1101 is -3, which is ~3 + 1
so if you want to get a negative number, you can simply do ~x + 1