Posted by : at

Category : 30_Days_of_Code


This challenge asks you to convert a number into binary and find the maximum number of consecutive 1’s.

Sample Input:

5 #101 in binary
13 #1101 in binary

Sample Output:

1
2

Longer Solution

The key to this problem is the math behind converting an integer into a binary number. The binary for a number n (e.g. n=13) can be found by taking the remainder 13%2 = 1, adding this resulting binary number to the front of a list [1], reassigning n = n//2 where // is the integer division 13//2 = 6, and again taking the remainder, 6%2 = 0, adding the resulting binary number to the front of a list [0, 1],… etc until it reaches 0. The loop to find a binary number is outlined below:

n = 13 #convert this to binary
binary_list = []
while(n > 0):
    remainder = n%2; #1 0 1 1
    n = n/2;  #6 3 1 0
    binary_list.insert(0, remainder)

print(binary_list) #[1,1,0,1]

Once you find the binary number, you can loop through this list to find the maximum number of consecutive 1’s.

In the code below, current_itr tracks the current number of consecutive 1’s while the loop is moving through the list. For the list [1,1,0,1], the current_itr is initially set to 0. As it loops through the list, it is set to 1 then 2 then 0 then 1.

max_1 is created to track the maximum number of consecutive 1’s seen so far in the loop. It is initially set to 0. If no 1’s are seen, it will remain 0. If the current_itr (current number of consecutive 1’s) is greater, max_1 is assigned this value. For the list [1,1,0,1], the max_1 is initially set to 0. It enters the loop and current_itr is 1. Already, a 1 is seen so the max_1 is set to 1. It loops again and current_itr becomes 2 since there is a second 1. This is greater than the current maximum so max_1 becomes 2. It loops again until current_itr becomes 0 and then 1. 1 is not greated than the maximum of 2 we have seen. So max_1 remains equal to 2.

l_bin = [1,1,0,1] 
max_1 = 0
current_itr = 0
for i in range(len(l_bin)):
    if l_bin[i] == 1:
        current_itr += 1
        if current_itr > max_1:
            max_1 = current_itr           
    else:
        current_itr = 0 
print(max_1)

Putting it all together, we calculate the binary value and then find the maximum number of consecutive 1’s.

Shorter Solution

I wanted to add in another solution that was very efficient. There is a function in Python called bin() that converts numbers into binary.

bin(13)
'0b1101'

The prefix ‘0b’ represents that the result is a binary string. You can remove this with indexing [2:].

bin(13)[2:]
'1101'

Now using the .split() function with ‘0’, we can remove the 0’s. The 1’s are grouped into the same strings.

bin(13)[2:].split('0')
bin(33)[2:].split('0')
['11', '1']
['1', '', '', '', '1']

What’s the longest string in the list? That’s the longest consecutive number of 1’s.

len(max(['11', '1']))
len(max(['1', '', '', '', '1']))

numbers = ['1', '', '', '', '1']
lengths = [len(num) for num in numbers] 
print(lengths)
print(max(lengths))
2
1

[1, 0, 0, 0, 1]
1

Sample Solution 1:

#!/bin/python3

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input()) #input base 10 number to convert to binary/base 2
    l_bin = [] #empty list
    
    while(n > 0):
        remainder = n%2;
        n = n//2;
        l_bin.insert(0, remainder)  #append remainder to the front of the list Insert remainder to front of a list or push onto a stack

    max_1 = 0
    current_itr = 0
    for i in range(len(l_bin)):
        if l_bin[i] == 1:
            current_itr += 1
            if current_itr > max_1:
                max_1 = current_itr           
        else:
            current_itr = 0 
    print(max_1)

Sample Solution 2:

#!/bin/python3

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input())
    binary_number <- bin(13)[2:].split('0')
    print(len(max(binary_number)))
About

Data Scientist with B.S. Statistics (3.8 GPA, Cum Laude) from UCLA. Programming knowledge includes R, Python, SQL, Tableau, SAS and other data analysis tools.

Star