def zero_count(n):
c = 0
while n > 0:
n, d = divmod(n, 10)
if d != 0:
return c
c += 1
return 1
print(zero_count(0))
print(zero_count(1))
print(zero_count(10))
print(zero_count(100100))
$ python zero_count.py
1
0
1
2
如果您想到带有字符串的选项:
def zero_count(n):
for i, d in enumerate(reversed(str(n))):
if d != '0':
return i
return 1
在字符串末尾计数零的正则表达式:
import re
def zero_count(n):
return len(re.search('0*$', str(n))[0])
num = 100100
zero_count = str(num)[::-1]
count = 0
# Не нужен тут цикл for, а вместо i сам count и используем
while zero_count[count] == '0':
count = count + 1
print(count)
选项 2(在原始 for 循环中更正):
num = 100100
zero_count = str(num)[::-1]
count = 0
for i in (range(0, len(zero_count))):
# Здесь нужен не бесконечный while, а if, если уж for использован
if zero_count[i] == '0':
count = count + 1
# А здесь прервать нужно, если условие не выполнено
else:
break
print(count)
你可以不用线。检查一个数可以被 10 整除多少次而没有余数:
如果您想到带有字符串的选项:
在字符串末尾计数零的正则表达式:
PS所有选项都适用于不太长的数字。但是如果你有一个非常大的数字并且它有很多零,那么有更好的方法......
摆脱无限循环的两种选择。更正在代码中通过注释进行解释。
选项1(两者中最好的):
选项 2(在原始 for 循环中更正):