# MIT Hakmem算法学习

#### 2. 思路

##### 2.3 问题转化

，将该思路带到上述二进制转时间至的以`2`为底的多项式中，但是首先需要对以`2`为底的多项式进行改造，

#### 3. 实现

`ai`表示的就是一个单位里二进制1的个数，那我们现在的任务就是计算着一个单位中的二进制`1`的个数是多少？

count = &0b000001 + (a>>1)&0b000001 +(a>>2)&0b000001 +(a>>3)&0b000001 +(a>>4)&0b000001 + (a >> 5)&0b000001

``````public static int bitCount(int n){
int t = (n & 010101010101)
+ ((n >>1) & 010101010101)
+ ((n >> 2) & 010101010101)
+ ((n >> 3) & 010101010101)
+ ((n >> 4) & 010101010101)
+ ((n >> 5) & 010101010101);
return t % 63;
}
``````

#### 4. 优化1

t = a & 0b001001 + (a>>1)&0b001001 + (a>>2)&0b001001;
t & 0b000111 + (t>>3)&0b000111

``````public static int bitCountI(int n){
int t = (n & 0b1001001001001001001001001001001)
+ ((n >> 1) & 0b1001001001001001001001001001001)
+ ((n >> 2) & 0b1001001001001001001001001001001);
t = (t + (t >> 3)) & 0b11000111000111000111000111000111;
return t % 63;
}

0b1001001001001001001001001001001 = 011111111111
0b11000111000111000111000111000111 = 030707070707
``````

#### 5. 优化2

4a+2b+c,此时我们要求a+b+c，于是我们将n>>1得2a+b，n>>2得a，

``````public static int bitCountIII(int n){
int t = n
- ((n>>1) & 0b11011011011011011011011011011011)
- ((n>>2) & 0b1001001001001001001001001001001);
t = (t + (t>>3)) & 0b11000111000111000111000111000111;
}
0b11011011011011011011011011011011 = 033333333333
0b1001001001001001001001001001001 = 011111111111
0b11000111000111000111000111000111 = 030707070707
``````