Python Map | Length of the Longest Consecutive 1’s in Binary Representation of a given integer
Last Updated :
27 Mar, 2023
Given a number n, find length of the longest consecutive 1s in its binary representation. Examples:
Input : n = 14
Output : 3
The binary representation of 14 is 1110.
Input : n = 222
Output : 4
The binary representation of 222 is 11011110.
We have existing solution for this problem please refer Length of the Longest Consecutive 1s in Binary Representation link. We can solve this problem quickly in python. Approach is very simple,
- Convert decimal number into it’s binary using bin() function and remove starting first two characters ‘0b’ because bin() function returns binary representation of number in string form and appends ‘0b’ as prefix.
- Separate all sub-strings of consecutive 1’s separated by zeros using split() method of string.
- Print maximum length of splitted sub-strings of 1’s.
Python3
def maxConsecutive1( input ):
input = bin ( input )
input = input [ 2 :]
print ( max ( map ( len , input .split( '0' ))))
if __name__ = = '__main__' :
input = 222
maxConsecutive1( input )
|
Time Complexity: O(n), where n is the number of bits in the binary representation of the input number.
Auxiliary Space: O(1), as the space used by the function is constant, regardless of the input size.
Approach#2: Using Bitwise Operations and Looping
The approach takes an integer input, converts it to its binary representation, loops through the binary string counting the consecutive ones, and returns the length of the longest consecutive ones.
Algorithm
1. Convert the given integer to binary string using the built-in bin() function.
2. Remove the ‘0b’ prefix from the binary string.
3. Initialize a counter variable ‘count’ to 0 and a temporary variable ‘temp_count’ to 0.
4. Loop through the binary string character by character.
5. If the current character is ‘1’, increment ‘temp_count’ by 1.
6. If the current character is ‘0’, update ‘count’ to max of ‘count’ and ‘temp_count’ and reset ‘temp_count’ to 0.
7. If the loop ends with ‘temp_count’ greater than ‘count’, update ‘count’ to ‘temp_count’.
8. Return ‘count’ as the length of the longest consecutive 1’s.
Python3
def longest_consecutive_ones(n):
binary_str = bin (n)[ 2 :]
count = 0
temp_count = 0
for bit in binary_str:
if bit = = '1' :
temp_count + = 1
else :
count = max (count, temp_count)
temp_count = 0
count = max (count, temp_count)
return count
n = 222
print (longest_consecutive_ones(n))
|
Time Complexity: O(log n) – The time complexity is logarithmic because we are iterating through the binary representation of the input integer.
Space Complexity: O(log n) – The space complexity is logarithmic because we are creating a binary string representation of the input integer.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...