DEV Community

M__
M__

Posted on

DAY 10: BINARY NUMBERS

Binary numbers represent a value in form of 1’s and 0’s. Python has a bin() method for converting integers to their binary format which makes the execution easy. However, the hard part comes when you have to get the number of consecutive 1’s in the binary value.

Such questions that ask to find the number of consecutive values in a sequence have been quite tough for me so anyone with tips on how to make such questions simpler to understand and work out, I would really appreciate the help.

The Task:
Given a base-10 integer, 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.

Top comments (2)

Collapse
 
udkumar profile image
uday kumar
n = int(input())
max_one_count = 0
one_count = 0

while n != 0:
    factor = n // 2
    remainder = n - 2 * factor
    n = factor
    if remainder == 1:
        one_count += 1
        max_one_count = max(max_one_count, one_count)
    else:
        one_count = 0

print(max_one_count)
Collapse
 
idimaimuna profile image
M__

Thank you so much.