简体   繁体   中英

You have a string that consist only of digits. You need to find how many zero digits ("0") are at the beginning of the given string

Our task is to count all the first zeros in the string of numbers, like '2333' should be counted as 0 and '00980' be 2 .

I have several questions regarding this.

  1. So I came up with this solution:
def beginning_zeros(a: str) -> int:
    if map(lambda x: x!=0, a): 
        s=str(int(a))
        return len(a)-len(s)
   
    return len(a)

it works well for the non-all-zero string, but why it returns len(a)-1 when it comes to all '0' string?

like beginning_zeros('000') should be 3 , but python count that as 2

and 2. about this solution:

def beginning_zero(a: str) -> int:

    a_num = int(a)
    if not a_num: # case a as all zeros

        return len(a)

    return len(a) - len(str(a_num))

it works perfectly, why is that not int(a) to execute the all-zero string? Is zero not counted int() ? or is there more explanation?

map(lambda x: x,= 0, a) returns map-object that's always True , and it goes straight into if-block, so

it works well for the non-all-zero string, but why it returns len(a)-1 when it comes to all '0' string?

hehe, it's because str(int('000')) is still '0' and len('0') is 1.

You just need a simple loop that examines the characters left to right as follows:

def leading_zeroes(s):
    r = 0
    for c in s:
        if c == '0':
            r += 1
        else:
            break
    return r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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