Consecutive Binary Ones

Category: Python Basics
Tags: Binary

Write a program that takes an integer as input, converts it to binary, and then returns the maximum number of consecutive 1’s in the binary representation.

Example:

Input: 13 

Output: 2

Convert the integer to binary using Python’s built-in bin function, which will return a string. You can then split this string on ‘0’ and find the length of the longest segment of ‘1’s.

def consecutive_ones(n):
binary = bin(n)[2:]
return max(map(len, binary.split('0')))

print(consecutive_ones(13)) # Outputs: 2

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!