PYTHON PROGRAMMING LANGUAGE

Hackerrank Binary Numbers Problem

To find the maximum number of consecutive 1’s in the binary number(base-2 representation) of a decimal number(base-10 representation).

Bipin P.
The Startup
Published in
4 min readNov 21, 2020

--

Image by Gordon Johnson from Pixabay

HackerRank is a technology hiring platform that assesses the developers of skills in various programming languages and multiple computer science domains. It also provides a lot of content to enhance one’s skills in programming. The binary numbers problem belongs to HackerRank’s 30 days of code challenge.

The objective is to find the maximum number of consecutive 1’s in the binary number(base-2 representation) of a decimal number(base-10 representation). As it involves counting the number of consecutive 1’s, we must access the next element while iterating through the loop and check whether these two elements are ones.

When two ones appear consecutively, a counter must be incremented. Hence, an input of 6 will have an output of 2. The real test lies when you are given input like 13(1101) or 103(1100111) or 524275(1111111111111110011). If you have not implemented code with appropriate condition checks, you will get erroneous output for them(e.g., 3 for 13 or 5 for 103).

As it involves counting the number of consecutive 1’s, we must access the next element while iterating through the loop and check whether these two elements are ones.

To know more about decimal to binary conversion, kindly visit my blog here:

The Code:

Let’s analyze the code.

if __name__ == ‘__main__’:

In Python, every module has a unique attribute called ‘__name__’. When the module is run as the main program, the attribute is set to ‘__main__’.

wholelist = []
n = int(input())
dec2bin(n)

An empty list ‘wholelist’ is created. The input decimal is received as n and the function ‘dec2bin’ is called.

global wholelist    
counter = 1
counter1 = 1
while(n/2>=1):
wholelist.append(int(n%2))
n /= 2

The ‘wholelist’ is declared as global. The global keyword creates a global variable and allows you to modify the variable outside of the current scope. The changes are made to the variable in a local context.

Two counters are initialized to 1. The input decimal is divided by 2 and the quotient thus obtained is then divided by 2. The process is continued until the quotient is 1. The remainder obtained in each step is added to the list(wholelist).

if(len(wholelist) > 1):
wholelist.reverse()
wholelist.insert(0, 1)

The order of elements in the list(remainders) is reversed to get the final binary number. This is done for every decimal except 1. Value of 1 is inserted as the first element of the list. This represents the last quotient of division by 2.

It is imperative to put wholelist.insert(0, 1) outside the if statement as the input ‘1’ returns an empty list(because of the condition ‘while(n/2>=1)’).

for idx,ele in enumerate(wholelist):
if(ele==1):
if(idx<(len(wholelist)-1)):
if(wholelist[idx+1]==1):
counter += 1
elif(wholelist[idx+1]==0):
counter1 = counter
pass

if((wholelist[idx-1]==0)&(ele==1)):
counter = 1
if(idx<(len(wholelist)-1)):
if(wholelist[idx+1]==1):
counter += 1

The enumerate() method adds a counter to an iterable and returns it in the form of an enumerate object. Here idx represents the counter and ele represents the elements in the list(iterator). If the element is one, then a condition is checked whether the counter is less than the length of the wholelist. This is done to prevent IndexError. If the next element is also one(consecutive ones), then the counter is incremented.

You may read more about IndexError arising out of accessing the next element here:

The elif statement(the equivalent of else if in C/C++) is to check if the next element is zero. If so, the counter1 is assigned the value of the counter. This is done so that if a number 103 is received as input, we can take account of two sets of consecutive ones(1100111).

The next if statement is to check if the previous number is zero and the current element is one. If so, then the counter is reset to one, and then a condition to prevent IndexError is checked(as explained earlier). If the next element turns out to be one, then the counter is incremented.

if(counter>counter1):
print(counter)
else:
print(counter1)

The largest amongst the counters is printed as the output. If the input was 103, counter > counter1 as there are more consecutive ones in the end(3 ones)than at the beginning(2 ones)of the binary representation of 103.

Hope you learned something new. Happy Coding!!!

References:

--

--

Bipin P.
The Startup

Data Science Enthusiast striving to secure greater goals