Count number of 1's in binary representation

后端 未结 21 2027
天涯浪人
天涯浪人 2020-11-28 01:32

Efficient way to count number of 1s in the binary representation of a number in O(1) if you have enough memory to play with. This is an interview question I found on an onli

21条回答
  •  执笔经年
    2020-11-28 02:06

    Below will work as well.

    nofone(int x) {
      a=0;
      while(x!=0) {
        x>>=1;
        if(x & 1)
          a++;
      }
      return a;
    } 
    

提交回复
热议问题