Count number of 1's in binary representation

后端 未结 21 2028
天涯浪人
天涯浪人 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 01:59

    Below are two simple examples (in C++) among many by which you can do this.

    1. We can simply count set bits (1's) using __builtin_popcount().

      int numOfOnes(int x) { return __builtin_popcount(x); }

    2. Loop through all bits in an integer, check if a bit is set and if it is then increment the count variable.

      int hammingDistance(int x) { int count = 0 for(int i = 0; i < 32; i++) if(x & (1 << i)) count++; return count; }

    Hope this helps!

提交回复
热议问题