- 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 1 in binary form of a number in C++

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++) −

## Example

#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); }

## Input

312

## Output

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
- Program to find length of longest consecutive path of a binary tree in python
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Python Program to Count number of binary strings without consecutive 1’
- Program to find number of boxes that form longest chain in Python?
- Program to find length of longest consecutive sequence in Python
- 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?
- Program to find concatenation of consecutive binary numbers in Python
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- Count number of binary strings without consecutive 1's in C
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- Program to find length of longest alternating path of a binary tree in python

Advertisements