Count number of 1's in binary representation

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

    Ruby implementation

    def find_consecutive_1(n)
      num = n.to_s(2)
      arr = num.split("")
      counter = 0
      max = 0
      arr.each do |x|
          if x.to_i==1
              counter +=1
          else
              max = counter if counter > max
              counter = 0 
          end
          max = counter if counter > max  
      end
      max
    end
    
    puts find_consecutive_1(439)
    

提交回复
热议问题