Count number of 1's in binary representation

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

    I had to golf this in ruby and ended up with

    l=->x{x.to_s(2).count ?1}
    

    Usage :

    l[2**32-1] # returns 32

    Obviously not efficient but does the trick :)

提交回复
热议问题