
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- C# 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
- Binary Tree Longest Consecutive Sequence in C++
- Python program to check if there are K consecutive 1’s in a binary number?
- C# program to check if there are K consecutive 1’s in a binary number
- Program to find length of longest alternating path of a binary tree in python

Advertisements