Skip to content

Instantly share code, notes, and snippets.

@lostinplace
Created August 2, 2016 17:31
Show Gist options
  • Save lostinplace/a42aef0653a80ee9db35fe108ce06fa1 to your computer and use it in GitHub Desktop.
Save lostinplace/a42aef0653a80ee9db35fe108ce06fa1 to your computer and use it in GitHub Desktop.
def count_set_bits(a_bv):
tmp = a_bv
next_i = 0
last_diff = 0
tmp_diff = 0
set_bits_count = 0
most_contiguous_set_bits = 0
current_contiguous_set_bits = 0
while tmp:
next_i = tmp & (tmp - 1)
last_diff = tmp_diff
tmp_diff = tmp - next_i
if not tmp_diff >> 1 == last_diff:
most_contiguous_set_bits = current_contiguous_set_bits
current_contiguous_set_bits = 0
current_contiguous_set_bits += 1
tmp = next_i
set_bits_count += 1
if current_contiguous_set_bits > most_contiguous_set_bits:
most_contiguous_set_bits = current_contiguous_set_bits
return set_bits_count, most_contiguous_set_bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment