# 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

Live Demo

#include<iostream>
using namespace std;
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) {
x = x << k;
p = p + k;
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

Updated on: 19-Dec-2019

101 Views 