
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find longest consecutive run of 1s in binary form of n in Python
Suppose we have a non-negative value n, we have to find the length of the longest consecutive run of 1s in its binary representation.
So, if the input is like n = 1469, then the output will be 4, because binary representation of 156 is "10110111101", so there are four consecutive 1s
To solve this, we will follow these steps −
- count := 0
- while n is not same as 0, do
- n := n AND (n after shifting one bit to the left)
- count := count + 1
- return count
Example
Let us see the following implementation to get better understanding −
def solve(n): count = 0 while n != 0: n = n & (n << 1) count = count + 1 return count n = 1469 print(solve(n))
Input
1469
Output
4
- Related Articles
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find length of longest consecutive path of a binary tree in python
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Program to find concatenation of consecutive binary numbers in Python
- Find the number of binary strings of length N with at least 3 consecutive 1s in C++
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find length of longest set of 1s by flipping k bits in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find longest subarray of 1s after deleting one element using Python
- Longest distance between 1s in binary JavaScript
- Program to find number of boxes that form longest chain in Python?

Advertisements