Count number of 1's in binary representation

后端 未结 21 2066
天涯浪人
天涯浪人 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:19

    I came here having a great belief that I know beautiful solution for this problem. Code in C:

        short numberOfOnes(unsigned int d) {
            short count = 0;
    
            for (; (d != 0); d &= (d - 1))
                ++count;
    
            return count;
        }
    

    But after I've taken a little research on this topic (read other answers:)) I found 5 more efficient algorithms. Love SO!

    There is even a CPU instruction designed specifically for this task: popcnt. (mentioned in this answer)

    Description and benchmarking of many algorithms you can find here.

提交回复
热议问题