简体   繁体   English

如何计算整数中的尾随零?

[英]How do I count the trailing zeros in integer?

I am trying to write a function that returns the number of trailing 0s in a string or integer.我正在尝试编写一个函数,该函数返回字符串或整数中尾随 0 的数量。 Here is what I am trying and it is not returning the correct values.这是我正在尝试的,它没有返回正确的值。

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

For strings, it is probably the easiest to use rstrip() :对于字符串,使用rstrip()可能是最简单的:

In [2]: s = '23989800000'

In [3]: len(s) - len(s.rstrip('0'))
Out[3]: 5

May be you can try doing this.也许你可以尝试这样做。 This may be easier than counting each trailing '0's这可能比计算每个尾随的“0”更容易

def trailing_zeros(longint):
    manipulandum = str(longint)
    return len(manipulandum)-len(manipulandum.rstrip('0'))

if you want to count how many zeros at the end of your int:如果您想计算 int 末尾有多少个零:

   def end_zeros(num):
        new_num = str(num)
        count = len(new_num) - len(new_num.rstrip("0"))
        return count



    print(end_zeros(0))  # == 1
    print(end_zeros(1))  # == 0
    print(end_zeros(10))  # == 1
    print(end_zeros(101))  # == 0
    print(end_zeros(245))  # == 0
    print(end_zeros(100100))  # == 2

Here are two examples of doing it:以下是执行此操作的两个示例:

  1. Using rstrip and walrus := operator .使用 rstrip 和walrus := operator Please notice that it only works in Python 3.8 and above.请注意,它仅适用于 Python 3.8 及更高版本。

def end_zeros(num):
    return len(s := str(num)) - len(s.rstrip("0"))
  1. Using findall() regular expression (re) function:使用 findall() 正则表达式 (re) 函数:

from re import findall
    
def end_zeros(num):
    return len(findall("0*$", str(num))[0])

String-Methods a quite clearly answered - here is one with keeping the integer. String-Methods 有一个很明确的回答——这是一个保留整数的方法。 You can get it also with using modulo (%) with 10 in the loop, and then reduce your given number by dividing it by then in the next loop:您也可以通过在循环中使用模数 (%) 和 10 来获得它,然后在下一个循环中通过除以 then 来减少给定的数字:

    def end_zeros(num: int):
        n = 0
        while num%10 == 0:
            n += 1
            num = num/10
            return n
        else:
            return 0

Without defining num as integer:没有将 num 定义为整数:

    def end_zeros(num):
        if num == 0:
            return 1
        elif num%10 == 0:
            n = 0
            while num%10 == 0:
                n += 1
                num = num/10
            return n
        else:
            return 0

You could just:你可以:

  1. Take the length of the string value of what you're checking取你正在检查的字符串值的长度
  2. Trim off trailing zeros from a copy of the string从字符串的副本中删除尾随零
  3. Take the length again, of the trimmed string再次取长度,修剪后的字符串
  4. Subtract the new length from the old length to get the number of zeroes trailing.从旧长度中减去新长度以获得尾随的零数。

I found two ways to achieve this, one is already mentioned above and the other is almost similar:我找到了两种方法来实现这一点,一种已经在上面提到过,另一种几乎相似:

manipulandum.count('0') - manipulandum.rstrip('0').count('0')

But still, I'm looking for some better answer.但是,我仍然在寻找更好的答案。

The question asks to count the trailing zeros in a string or integer .该问题要求计算 string或 integer 中的尾随零。 For a string, len(s) - len(s.rstrip('0')) is fine.对于字符串, len(s) - len(s.rstrip('0'))很好。 But for an integer, presumably you don't want to convert it to a string first.但是对于整数,大概您不想先将其转换为字符串。 In that case, use recursion:在这种情况下,使用递归:

def trailing_zeros(longint):
    assert(longint)
    return ~longint % 2 and trailing_zeros(longint/2) + 1

Here are two examples of doing it:以下是执行此操作的两个示例:

  1. Using rstrip and walrus := operator.使用 rstrip 和 walrus := 运算符。 Please notice that it only works in Python 3.8 and above.请注意,它仅适用于 Python 3.8 及更高版本。

    def end_zeros(num): return len(s := str(num)) - len(s.rstrip("0")) def end_zeros(num): return len(s := str(num)) - len(s.rstrip("0"))

  2. Using re.findall() function:使用 re.findall() 函数:

    from re import findall从重新导入 findall

    def end_zeros(num): return len(findall("0*$", str(num))[0]) def end_zeros(num): return len(findall("0*$", str(num))[0])

You can use bitwise operators:您可以使用按位运算符:

>>> def trailing_zeros(x):
...     return (x & -x).bit_length() - 1
... 
>>> trailing_zeros(0b0110110000)
4
>>> trailing_zeros(0b0)
-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM