same number of one's bit
写了大概一下午,本以为很easy的,写了才知道“边界+细节”,尤其“(ones >> 2) >> ntz”,如果写成了“ones>>(2+ntz)"就会报错,边界部分自己调了。
关于bitcount部分,做了修改,基本只用一个大的常数,以及一些小的数字。
4 int bitcount(unsigned int n)
5 {
6 unsigned int tmp;
7 tmp = n & 0x33333333;
8 n = n - tmp;
9 n = (n >> 2) & 0x33333333;
10 tmp = tmp - ((tmp >> 1) & 0x33333333);
11 n = n - ((n >> 1) & 0x33333333);
12 tmp = tmp + n;
13 n = tmp + (tmp >> 16);
14 tmp = (n & 0xf) + ((n >> 4) & 0xf) +
15 ((n >> 8) & 0xf) + ((n >> 12) & 0xf);
16 tmp = tmp & 0xff;
17 return tmp;
18 }
19
20
21 unsigned int snoob(unsigned int n)
22 {
23 unsigned int smallest, ripple, ones, ntz;
24 smallest = n & (-n);
25 ntz = bitcount (smallest-1);
26 ripple = n + smallest;
27 ones = n ^ ripple;
28 if(ones != n )
29 ones = (ones >> 2) >> ntz;
30 n = ripple | ones;
31 return n;
32 }