Search code examples
pythonstringlist

Efficient code to count the number of trailing 0s at the end of a binary number


I was looking into a method for finding the number of trailing zeros in binary numbers and came across a solution in C (link). I am looking for a solution in Python!

Binary Input -> 1000
Output: 3

Binary Input -> 101101001100
Output: 2

Binary Input -> 1010001010000
Output: 4

Binary Input -> 100000001
Output: 0

Is there an efficient way of doing this without iterating the binary number as a string or using string methods for filtering? Basically, I may have a very large number of very very large binary numbers, so I am trying to find something more efficient than simply iterating over it as a string.


EDIT:

Here is my attempt -

def trailingzeros(l):
    count = 0
    a = [i for i in str(l)]
    for i in reversed(a):
        if i=='0':
            count+=1
        else:
            break
    return count

NOTE: I am looking for a solution that exploits the binary nature of the input.


Solution

  • n = 0b1010001010000
    
    count = 0
    while n:
        if (n&1):
            break
        n >>= 1
        count += 1
    
    print(count)
    

    Prints:

    4