dimanche 26 avril 2020

what happens if I interchange the if and else statements?

I solved a problem with the coding platform and there are if-else statements that had a great impact on the results, but I am not getting why this was happening.

SPOILER:- this code is the solution to the Day10: Binary numbers of hackerrank '30 days of code' The problem statement was as:

Task Given a base-10integer,n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.

Sample Input 1

5

Sample Output 1

1

the correct code for this is:

    n = int(input())
    b=str(bin(n))
    count=0
    res=0
    for i in b:
        if(i=='1'):
            count+=1
            res=max(res,count)
        else:
            count=0      
print(res)

But if I changed the if-else statements as:

 n = int(input())
b=str(bin(n))
count=0
res=0
for i in b:
    if(i=='0'):
        count=0      
    else:
        count+=1
        res=max(res,count)

print(res)

For this interchanged if-else statements I am getting a wrong output as:

Sample Input 1

5

Sample Output 1

2

I am not getting this why the count is not assigned to zero in the interchanged if-else statement or what is the difference between the above two-piece of codes, please help.

Aucun commentaire:

Enregistrer un commentaire