How to implement Bitcount using only Bitwise operators?

后端 未结 4 1134
一生所求
一生所求 2020-11-29 02:14

The task is to implement a bit count logic using only bitwise operators. I got it working fine, but am wondering if someone can suggest a more elegant approach.

Onl

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:57

    Several interesting solutions here.

    If the solutions above are too boring, here is a C recursive version exempt of condition test or loop:

      int z(unsigned n, int count);
      int f(unsigned n, int count);
    
      int (*pf[2])(unsigned n, int count) = { z,f };
    
      int f(unsigned n, int count)
      {
         return (*pf[n > 0])(n >> 1, count+(n & 1));
      }
    
      int z(unsigned n, int count)
      {
         return count;
      }
    
      ...
      printf("%d\n", f(my_number, 0));
    

提交回复
热议问题