- Trending Categories
- 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

# Find consecutive 1s of length >= n in binary representation of a number in C++

Suppose, we have two integers x and n, our task is to search for the first consecutive stream of 1s (32-bit binary) which is greater than or equal to the value of n in length and return its position. If no such string exists, then return -1. For example, if x = 35, and n = 2, then result will be 31. The binary representation of 35 in a 32-bit integer is like −

00000000000000000000000000100011. So two consecutive 1s are present at index 31, so the answer is 31.

To solve this problem, we have to find the number of leading zeros, and from that count, we will try to find the consecutive 1s. Let us see the example to get a better idea.

## Example

#include<iostream> using namespace std; int leadingZeroCount(int x) { unsigned y; int n; n = 32; for(int i = 16; i > 1; i = i/2 ){ y = x >> i; if(y != 0){ n -= i; x = y; } } y = x >> 1; if (y != 0) return n - 2; return n - x; } int consecutiveOnePosition(unsigned x, int n) { int k, p; p = 0; while (x != 0) { k = leadingZeroCount(x); x = x << k; p = p + k; k = leadingZeroCount(~x); if (k >= n) return p + 1; x = x << k; p = p + k; } return -1; } int main() { int x = 35; int n = 2; cout << "Consecutive 1s of length " << n << " is starting from index: " << consecutiveOnePosition(x, n); }

## Output

Consecutive 1s of length 2 is starting from index: 31

Advertisements