Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Counting number of enabled bits in uint32_t.. Here is a O(lg32) solution. Very smart, like bottom-up parallel tree post-order traversal.

Solution from discussion of LC:

int hammingWeight(uint32_t n) 
{ n
= ((n >> (1 << 0)) & 0x55555555) + (n & 0x55555555); n = ((n >> (1 << 1)) & 0x33333333) + (n & 0x33333333); n = ((n >> (1 << 2)) & 0x0F0F0F0F) + (n & 0x0F0F0F0F); n = ((n >> (1 << 3)) & 0x00FF00FF) + (n & 0x00FF00FF); return ((n >> (1 << 4)) & 0xFFFF) + (n & 0xFFFF); }

 

posted on 2015-03-12 01:41  Tonix  阅读(168)  评论(0编辑  收藏  举报