Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers x and n, the task is to search for the first consecutive stream of 1s (in the x’s 32-bit binary representation) which is greater than or equal to n in length and return its position. If no such string exists then return -1.
Examples: 

Input: x = 35, n = 2 
Output: 31 
Binary representation of 35 is 00000000000000000000000000100011 and two consecutive 1’s are present at position 31.

Input: x = 32, n = 3 
Output: -1 
32 = 00000000000000000000000000100000 in binary and it does not have a sub-string of 3 consecutive 1’s. 

Approach: Use Bitwise operation to calculate the no. of leading zeros in the number and then use it to find the position from where we need to start searching for consecutive 1’s. Skip the search for leading zeros.
Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the
// number of leading zeros
int countLeadingZeros(int x)
{
    unsigned y;
    int n;
    n = 32;
    y = x >> 16;
    if (y != 0) {
        n = n - 16;
        x = y;
    }
    y = x >> 8;
    if (y != 0) {
        n = n - 8;
        x = y;
    }
    y = x >> 4;
    if (y != 0) {
        n = n - 4;
        x = y;
    }
    y = x >> 2;
    if (y != 0) {
        n = n - 2;
        x = y;
    }
    y = x >> 1;
    if (y != 0)
        return n - 2;
    return n - x;
}
 
// Function to find the string
// of n consecutive 1's
int FindStringof1s(unsigned x, int n)
{
    int k, p;
 
    // Initialize position to return.
    p = 0;
    while (x != 0) {
 
        // Skip leading 0's
        k = countLeadingZeros(x);
        x = x << k;
 
        // Set position after leading 0's
        p = p + k;
 
        // Count first group of 1's.
        k = countLeadingZeros(~x);
 
        // If length of consecutive 1's
        // is greater than or equal to n
        if (k >= n)
            return p + 1;
 
        // Not enough 1's
        // skip over to next group
        x = x << k;
 
        // Update the position
        p = p + k;
    }
 
    // if no string is found
    return -1;
}
 
// Driver code
int main()
{
    int x = 35;
    int n = 2;
    cout << FindStringof1s(x, n);
}


Java




// Java  implementation of above approach
 
import java.io.*;
 
class GFG {
// Function to count the
// number of leading zeros
static int countLeadingZeros(int x)
{
    int y;
    int n;
    n = 32;
    y = x >> 16;
    if (y != 0) {
        n = n - 16;
        x = y;
    }
    y = x >> 8;
    if (y != 0) {
        n = n - 8;
        x = y;
    }
    y = x >> 4;
    if (y != 0) {
        n = n - 4;
        x = y;
    }
    y = x >> 2;
    if (y != 0) {
        n = n - 2;
        x = y;
    }
    y = x >> 1;
    if (y != 0)
        return n - 2;
    return n - x;
}
 
// Function to find the string
// of n consecutive 1's
static int FindStringof1s(int x, int n)
{
    int k, p;
 
    // Initialize position to return.
    p = 0;
    while (x != 0) {
 
        // Skip leading 0's
        k = countLeadingZeros(x);
        x = x << k;
 
        // Set position after leading 0's
        p = p + k;
 
        // Count first group of 1's.
        k = countLeadingZeros(~x);
 
        // If length of consecutive 1's
        // is greater than or equal to n
        if (k >= n)
            return p + 1;
 
        // Not enough 1's
        // skip over to next group
        x = x << k;
 
        // Update the position
        p = p + k;
    }
 
    // if no string is found
    return -1;
}
 
// Driver code
     
    public static void main (String[] args) {
 
    int x = 35;
    int n = 2;
    System.out.println(FindStringof1s(x, n));
    }
}


C#




// C# implementation of above approach
 
using System;
 
public class GFG{
     
// Function to count the
// number of leading zeros
static int countLeadingZeros(int x)
{
    int y;
    int n;
    n = 32;
    y = x >> 16;
    if (y != 0) {
        n = n - 16;
        x = y;
    }
    y = x >> 8;
    if (y != 0) {
        n = n - 8;
        x = y;
    }
    y = x >> 4;
    if (y != 0) {
        n = n - 4;
        x = y;
    }
    y = x >> 2;
    if (y != 0) {
        n = n - 2;
        x = y;
    }
    y = x >> 1;
    if (y != 0)
        return n - 2;
    return n - x;
}
 
// Function to find the string
// of n consecutive 1's
static int FindStringof1s(int  x, int n)
{
    int k, p;
 
    // Initialize position to return.
    p = 0;
    while (x != 0) {
 
        // Skip leading 0's
        k = countLeadingZeros(x);
        x = x << k;
 
        // Set position after leading 0's
        p = p + k;
 
        // Count first group of 1's.
        k = countLeadingZeros(~x);
 
        // If length of consecutive 1's
        // is greater than or equal to n
        if (k >= n)
            return p + 1;
 
        // Not enough 1's
        // skip over to next group
        x = x << k;
 
        // Update the position
        p = p + k;
    }
 
    // if no string is found
    return -1;
}
 
// Driver code
     
    static public void Main (){
    int x = 35;
    int n = 2;
    Console.WriteLine (FindStringof1s(x, n));
    }
}


Javascript




<script>
// Javascript implementation of above approach
 
 
// Function to count the
// number of leading zeros
function countLeadingZeros(x) {
    let y;
    let n;
    n = 32;
    y = x >> 16;
    if (y != 0) {
        n = n - 16;
        x = y;
    }
    y = x >> 8;
    if (y != 0) {
        n = n - 8;
        x = y;
    }
    y = x >> 4;
    if (y != 0) {
        n = n - 4;
        x = y;
    }
    y = x >> 2;
    if (y != 0) {
        n = n - 2;
        x = y;
    }
    y = x >> 1;
    if (y != 0)
        return n - 2;
    return n - x;
}
 
// Function to find the string
// of n consecutive 1's
function FindStringof1s(x, n) {
    let k, p;
 
    // Initialize position to return.
    p = 0;
    while (x != 0) {
 
        // Skip leading 0's
        k = countLeadingZeros(x);
        x = x << k;
 
        // Set position after leading 0's
        p = p + k;
 
        // Count first group of 1's.
        k = countLeadingZeros(~x);
 
        // If length of consecutive 1's
        // is greater than or equal to n
        if (k >= n)
            return p + 1;
 
        // Not enough 1's
        // skip over to next group
        x = x << k;
 
        // Update the position
        p = p + k;
    }
 
    // if no string is found
    return -1;
}
 
// Driver code
let x = 35;
let n = 2;
document.write(FindStringof1s(x, n));
 
// This code is contributed by gfgking.
</script>


Output

31

Approach: Using predefined functions

x can be converted to a binary string using in-built methods, such as bitset<32>(x).to_string() in C++ STL, bin() in Python3, Integer.toBinary() in Java . And, a string of n 1s can be constructed, whose index in the binary string can be located using predefined functions such as find in C++ STL, index in Python3 and indexOf() in Java.

This approach can be summarized to the following steps:

1. Form the binary string equivalent of the number using in-built methods, such as bitset<32>(x).to_string() in C++ STL, bin() in Python3, Integer.toBinary() in Java.

2. Then, build a string consisting of n 1s, using in-built methods, such as string (n, ‘1’) in C++ STL, ‘1’ * n in Python3, and “1”.repeat(n) in Java.

3. Then, find the index of the string of n 1s in the binary string using in-built methods such as .find() in C++ STL, index() in Python3 and indexOf() in Java.
 

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the string
// of n consecutive 1's
int FindStringof1s(unsigned x, int n)
{
    // converting x to a binary string
    string bin = bitset<32>(x).to_string();
 
    // constructing a string of n 1s
    string ones(n, '1');
 
    // locating the ones string in bin
    auto pos = bin.find(ones);
    if (pos != string::npos)
        return pos + 1;
 
    // if no string is found
    return -1;
}
 
// Driver code
int main()
{
    int x = 35;
    int n = 2;
 
    // Function call
    cout << FindStringof1s(x, n);
}
 
// This code is contributed by phasing17


Java




import java.util.Arrays;
 
public class GFG {
    // Function to find the string of n consecutive 1's
    public static int FindStringof1s(int x, int n) {
        // converting x to a binary string
        String bin = String.format("%32s", Integer.toBinaryString(x)).replace(' ', '0');
 
        // constructing a string of n 1s
        char[] onesArray = new char[n];
        Arrays.fill(onesArray, '1');
        String ones = new String(onesArray);
 
        // locating the ones string in bin
        int pos = bin.indexOf(ones);
        if (pos != -1)
            return pos + 1;
 
        // if no string is found
        return -1;
    }
 
    // Driver code
    public static void main(String[] args) {
        int x = 35;
        int n = 2;
 
        // Function call
        System.out.println(FindStringof1s(x, n));
    }
}


Python3




# Python3 implementation of above approach
 
 
# Function to find the string
# of n consecutive 1's
def FindStringof1s(x, n):
 
    # converting x to a binary string
    bin_ = bin(x).zfill(32)
 
    # constructing a string of n 1s
    ones = n * "1"
 
    # locating the ones string in bin
    if ones in bin_:
        return bin_.index(ones) + 1
 
    # if no string is found
    return -1;
 
 
# Driver code
x = 35
n = 2
 
# Function call
print(FindStringof1s(x, n))
 
 
 
# This code is contributed by phasing17


C#




using System;
 
public class GFG
{
// Function to find the string
// of n consecutive 1's
public static int FindStringof1s(uint x, int n)
{
// converting x to a binary string
string bin = Convert.ToString(x, 2).PadLeft(32, '0');
      // constructing a string of n 1s
    string ones = new string('1', n);
 
    // locating the ones string in bin
    int pos = bin.IndexOf(ones);
    if (pos != -1)
        return pos + 1;
 
    // if no string is found
    return -1;
}
 
// Driver code
public static void Main()
{
    uint x = 35;
    int n = 2;
 
    // Function call
    Console.WriteLine(FindStringof1s(x, n));
}
}


Javascript




function FindStringof1s(x, n) {
  // converting x to a binary string
  let bin = x.toString(2).padStart(32, '0');
 
  // constructing a string of n 1s
  let ones = '1'.repeat(n);
 
  // locating the ones string in bin
  let pos = bin.indexOf(ones);
  if (pos != -1)
    return pos + 1;
 
  // if no string is found
  return -1;
}
 
// Driver code
let x = 35;
let n = 2;
 
// Function call
console.log(FindStringof1s(x, n));


Output

31

Time Complexity: O(log n)
Auxiliary Space: O(1)



Last Updated : 14 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads