This is what I came up with:
def leading_zeros_counter(x: str):
zeros = 0
for i in x:
if i == str(0):
zeros += 1
else:
return int(zeros)
It seems to work on all strings, unless the string contains all zeros (e.g. ‘0000’ does not return ‘4’). Can anyone one explain why, and how to fix this?
>Solution :
You need to add a return statement out of the if condition:
def leading_zeros_counter(x: str):
zeros = 0
for i in x:
if i == "0":
zeros += 1
else:
return int(zeros)
return int(zeros)
print(leading_zeros_counter("0000"))
So the output would be:
4