- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements