- Related Questions & Answers
- Find the number of binary strings of length N with at least 3 consecutive 1s in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Sorting according to number of 1s in binary representation using JavaScript
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Find row number of a binary matrix having maximum number of 1s in C++
- Calculating 1s in binary representation of numbers in JavaScript
- Binary representation of a given number in C++
- XOR counts of 0s and 1s in binary representation in C++
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Number of leading zeros in binary representation of a given number in C++
- Program to find length of longest consecutive path of a binary tree in python

- 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 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.

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

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

Advertisements