Python Map | Length of longest sequential 1 in binary representation of a given integer

Python Methods and Functions

Examples:

 Input: n = 14 Output: 3 The binary representation of 14 is  111  0. Input: n = 222 Output: 4 The binary representation of 222 is 110  1111  0. 

We have a solution to this problem, please refer to Length of longest sequential 1 in binary . We can fix this problem quickly in Python. The approach is very simple,

  1. Convert decimal to binary using bin () function returns the binary representation of a number in string form and prefixes 0b.
  2. Separate all substrings of consecutive 1s, separated by zeros, with using the string method split () .
  3. Print the maximum length of split substrings from 1.

# Function to find the length of the longest sequential
# 1 in binary

  

def maxConsecutive1 ( input ):

< code class = "comments"> # convert number to binary

input = bin ( input )

 

# remove the first two characters of the output line

input = input [ 2 :]

  

# input.split (& # 39; 0 & # 39;) - & gt; breaks all substrings

# consecutive 1s separated by 0, the output will be

# be like [& # 39; 11 & # 39 ;, & # 39; 1111 & # 39;]

# map (len, input.split (& # 39; 0 & # 39;)) - & gt; map map functions

Function # len in each substring of consecutive 1

# max () returns the maximum item in the list

  print ( max ( map ( len , input . split ( '0 ' ))))

  
# Driver program

if __ name__ = = '__main__' :

  input = 222

maxConsecutive1 ( input )

Output:

 4 




Tutorials