- 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

Suppose we have a number 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 = 312, then the output will be 3, as 312 is 100111000 in binary and there are 3 consecutive 1s.

To solve this, we will follow these steps −

ret := 0, len := 0

for initialize i := 0, when i < 32, update (increase i by 1), do:

if n/2 is odd, then

(increase len by 1)

Otherwise

len := 0

ret := maximum of ret and len

return ret

Let us see the following implementation to get better understanding:

Source Code (C++) −

#include <bits/stdc++.h> using namespace std; class Solution { public: int solve(int n) { int ret = 0; int len = 0; for(int i = 0; i < 32; i++){ if((n >> i) & 1){ len++; }else{ len = 0; } ret = max(ret, len); } return ret; } }; main(){ Solution ob; cout << ob.solve(312); }

312

3

- Related Questions & Answers
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find longest distance of 1s in binary form of a number using Python
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Program to find length of longest consecutive path of a binary tree in python
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Python Program to Count number of binary strings without consecutive 1’
- Program to find number of boxes that form longest chain in Python?
- Count number of binary strings without consecutive 1's in C
- Program to find length of longest consecutive sequence in Python
- Binary Tree Longest Consecutive Sequence in C++
- Find the Number of 1 Bits in a large Binary Number in C++
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Binary Tree Longest Consecutive Sequence II in C++

Advertisements