Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count trailing and leading zeroes in Python
def count_lead_and_trail_zeroes(d):
"""Count the number of leading and trailing zeroes in an integer."""
b = "{:064b}".format(d)
try:
return as_str.index("1"), 63 - as_str.rindex("1")
except ValueError:
return 64, 64
def count_lead_and_trail_zeroes(d):
# https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear
if d:
v = (d ^ (d - 1) >> 1) # Set v's trailing 0s to 1s and zero rest
trailing = 0
while v:
v >>= 1
trailing += 1
leading = 64
v = d
while v:
v >>= 1
leading -= 1
return leading, trailing
return 64, 64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.