在Python中,如何计算字符串或整数中的尾随零?

Fri*_*che 11 python string

我正在尝试编写一个函数,它返回字符串或整数中的尾随0的数量.这是我正在尝试的,它没有返回正确的值.

def trailing_zeros(longint):
    manipulandum = str(longint)
    x = 0
    i = 1
    for ch in manipulandum:
        if manipulandum[-i] == '0':
            x += x
            i += 1
        else:
            return x
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 28

对于字符串,它可能是最容易使用的rstrip():

In [2]: s = '23989800000'

In [3]: len(s) - len(s.rstrip('0'))
Out[3]: 5
Run Code Online (Sandbox Code Playgroud)


Abh*_*jit 12

也许你可以尝试这样做.这可能比计算每个尾随'0'更容易

def trailing_zeros(longint):
    manipulandum = str(longint)
    return len(manipulandum)-len(manipulandum.rstrip('0'))
Run Code Online (Sandbox Code Playgroud)


Be3*_*K0T 5

您可以使用按位运算符:

>>> def trailing_zeros(x):
...     return (x & -x).bit_length() - 1
... 
>>> trailing_zeros(0b0110110000)
4
>>> trailing_zeros(0b0)
-1
Run Code Online (Sandbox Code Playgroud)