找出数字最后有多少个零(数字为0时字符串索引超出范围错误)

我正在尝试解决标题中的问题,但出现 IndexError。

def count_zeros(number:int) -> int:
    number = str(number)
    i = 0
    j = -1

    while number[j] == '0'
        i += 1
        j += -1

    return i

仅当数字为 0 时,此代码才会吐出 IndexError。我不知道为什么。

>>>count_zeros(0)


IndexError  Traceback (most recent call last)
<ipython-input-45-688099e7700c> in <module>
----> 1 end_zeros(0)

<ipython-input-43-181de92af60c> in end_zeros(number)
      4     i = 0
      5 
----> 6     while number[j] == '0':
      7         i += 1
      8         j -= 1

IndexError: string index out of range

回答

我会在这里使用模数并计算右侧的零数:

def count_zeros(number:int) -> int:
    if number == 0:
        return 1
    else:
        count = 0
        while True:
            if number % 10 != 0 or number == 0:
                 break
            count = count + 1 
            number = number / 10

        return count

这种方法很简单,几乎肯定会优于将输入整数转换为字符串然后检查尾随零。


以上是找出数字最后有多少个零(数字为0时字符串索引超出范围错误)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>