data lab其实就是一大堆的quiz合到一起,基本互相之间没太大关系。
所有题目可以分为三个类型:基本位操作,补码和浮点数。
今天就做了基本位操作,其中有一道叫bitCount的题蛮难的,卡了半天。
题目如下:
/*
* bitCount - returns count of number of 1's in word
* Examples: bitCount(5) = 2, bitCount(7) = 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 40
* Rating: 4
*/
int bitCount(int x) {
int a1 = 0x00000055;
int b1 = a1 + (a1 << 8);
int c1 = b1 + (b1 << 16);
int d = (x & c1) + ((x >> 1) & c1);
int a2 = 0x00000033;
int b2 = a2 + (a2 << 8);
int c2 = b2 + (b2 << 16);
int num1 = (d & c2) + ((d >> 2) & c2);
int a3 = 0x0000000f;
int b3 = a3 + (a3 << 8);
int c3 = b3 + (b3 << 16);
int num2 = (num1 & c3) + ((num1 >> 4) & c3);
int a4 = 0x000000ff;
int c4 = a4 + (a4 << 16);
int num4 = (num2 & c4) + ((num2 >> 8) & c4);
int c5 = a4 + (a4 << 8);
int num8 = (num4 & c5) + ((num4 >> 16) & c5);
return num8;
}