Python Map | Length of the Longest Consecutive 1’s in Binary Representation of a given integer
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.
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.
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.
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.
Please Login to comment...