-2

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.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • As mentioned in the question, I am looking for a solution in python and not in C as answered by this question https://stackoverflow.com/questions/7812044/finding-trailing-0s-in-a-binary-number – Akshay Sehgal Oct 19 '20 at 11:37
  • 1
    https://meta.stackoverflow.com/questions/265825/code-translation-tagging – Martheen Oct 19 '20 at 11:56

2 Answers2

3
n = 0b1010001010000

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

print(count)

Prints:

4
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 2
    This solutions uses binary and (`n & 1`) and shift (`n >>=1`) which are as optimized as you can get with Python. +1 – Adirio Oct 19 '20 at 11:45
  • Thanks this works. i was looking for binary operations to exploit instead of string operations. – Akshay Sehgal Oct 19 '20 at 11:50
1

You can use python bit operators:

def findTrailing0(num):
    count = 0
    lastBit = 0
    while num != 0:
        lastBit = num & 0x1
        if lastBit != 0:
            break
        count += 1
        num >>= 1
    return count
napuzba
  • 6,033
  • 3
  • 21
  • 32