- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- 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
- Find the number of binary strings of length N with at least 3 consecutive 1s in C++
- Program to find concatenation of consecutive binary numbers in Python
- 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 substring with 1s in a binary string after one 0-flip in Python
- Program to find number of boxes that form longest chain in Python?
- Program to find longest subarray of 1s after deleting one element using Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Longest distance between 1s in binary JavaScript

Advertisements