Last active
May 29, 2024 10:09
-
-
Save jd/303809d1f6c6425cf5e9 to your computer and use it in GitHub Desktop.
Count trailing and leading zeroes in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I know it is a gist from 2016, but since it shows up in google search I would like to clarify that the first function probably should have
as_str
replaced withb
becauseas_str
is undefined.this is how it would look like:
def count_lead_and_trail_zeroes(d):
"""Count the number of leading and trailing zeroes in an integer."""
b = "{:064b}".format(d)
try:
return b.index("1"), 63 - b.rindex("1")
except ValueError:
return 64, 64