Snowdream

posts - 403, comments - 310, trackbacks - 0, articles - 7
BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

1:  int Count(int v)
2:  {
3:      int num = 0;
4:      while (v) {
5:          num += v & 0x01;
6:          v >>= 1;
7:      }
8:      return num;
9:  }

1:  int countTable[256] = { 0, 1, 1, 2, 1, ..., 7, 7, 8 };
2:
3:  int Count(int v) {
4:      return countTable[v];
5:  }

1:  int Count(unsigned x) {
2:     x = x - ((x >> 1) & 0x55555555);
3:     x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
4:     x = (x + (x >> 4)) & 0x0F0F0F0F;
5:     x = x + (x >> 8);
6:     x = x + (x >> 16);
7:     return x & 0x0000003F;
8:  }

1:  int Count(unsigned x) {
2:     unsigned n;
3:
4:     n = (x >> 1) & 033333333333;
5:     x = x - n;
6:     n = (n >> 1) & 033333333333;
7:     x = x - n;
8:     x = (x + (x >> 3)) & 030707070707;
9:     x = modu(x, 63);
10:     return x;
11:  }

(by ZelluX   http://www.blogjava.net/zellux)

评论

mod是一个异常慢的操作……
You cannot judge the performance of an algorithm by calculating its time complexity. You should first convert code into opcode and then calculate. This is more fairer.
@Lee.MaRS

@stanleyxu

>>总体看来这本书还是很不错的，比较喜欢里面针对一个问题提出不同算法并不断改进的风格。

 只有注册用户登录后才能发表评论。 网站导航: 相关文章: