Open In App

Count of Non-Negative Integers that doesn’t contain consecutive ones

Improve
Improve
Like Article
Like
Save
Share
Report

Given a range of integers, the task is to find the numbers of Non-Negative Integers which doesn’t contain consecutive ones (1s) in their binary representation.

Examples:

Input: [0, 7]
Output: 5

Input: [0, 10]
Output: 8

Input: [2, 10]
Output: 6

Approach: This code uses the following approach to find the number of non-negative integers in the given range whose binary representation does not contain consecutive ones:

  • Input the range “n” and “m”.
  • Create a “result” counter “result” and initialize it to zero.
  • Loop through each integer “i” in the range [n, m].
  • Convert the integer “i” to its binary representation using the “bitset” class in C++.
  • Create a boolean variable “foundConsecutiveOnes” and initialize it to “false”.
  • Loop through each bit in the binary representation of “i”.
  • Check if the current bit and the next bit are both set to 1. If they are, set “foundConsecutiveOnes” to true and break out of the loop.
  • If “foundConsecutiveOnes” is “false”, increment the “result” counter result by 1.
  • Repeat steps 3 to 8 for each integer in the range [n, m].
  • Return the value of the “result” counter “result” as the final answer.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of
// non-negative integers which doesn't
// contains consecutive ones in the given
// range of Integers.
int countNonNegIntegers(int n, int m)
{
    int result = 0;
    for (int i = n; i <= m; i++) {
        bitset<32> b(i);
        bool foundConsecutiveOnes = false;
        for (int j = 0; j < b.size() - 1; j++) {
            if (b[j] == 1 && b[j + 1] == 1) {
                foundConsecutiveOnes = true;
                break;
            }
        }
        if (!foundConsecutiveOnes)
            result++;
    }
    return result;
}
 
// Driver code
int main()
{
    int n = 2;
    int m = 12;
 
    // Function call
    cout << "The number of non-negative integers in the "
            "range ["
         << n << ", " << m
         << "] whose binary representation does not "
            "contain consecutive ones is: "
         << endl
         << countNonNegIntegers(n, m) << endl;
    return 0;
}


Java




// Java code for the above approach:
import java.util.BitSet;
class GFG {
 
  // Function to find the count of
  // non-negative integers which doesn't
  // contains consecutive ones in the given
  // range of Integers.
  public static int countNonNegIntegers(int n, int m)
  {
    int result = 0;
    for (int i = n; i <= m; i++) {
      BitSet b = BitSet.valueOf(new long[] { i });
      boolean foundConsecutiveOnes = false;
      for (int j = 0; j < b.length() - 1; j++) {
        if (b.get(j) && b.get(j + 1)) {
          foundConsecutiveOnes = true;
          break;
        }
      }
      if (!foundConsecutiveOnes) {
        result++;
      }
    }
    return result;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int n = 2;
    int m = 12;
 
    // Function call
    System.out.println(
      "The number of non-negative integers in the range ["
      + n + ", " + m
      + "] whose binary representation does not contain consecutive ones is: "
      + countNonNegIntegers(n, m));
  }
}
 
// This Code is Contributed by Prasad Kandekar(prasad264)


C#




// C# code for the above approach:
 
using System;
 
public class GFG {
 
    // Function to find the count of non-negative integers
    // which doesn't contains consecutive ones in the given
    // range of Integers.
    public static int CountNonNegIntegers(int n, int m)
    {
        int result = 0;
        for (int i = n; i <= m; i++) {
            int number = i;
            int count = 0;
            bool[] binary = new bool[32];
            while (number > 0) {
                binary[count++] = (number & 1) == 1;
                number >>= 1;
            }
            bool foundConsecutiveOnes = false;
            for (int j = 0; j < count - 1; j++) {
                if (binary[j] && binary[j + 1]) {
                    foundConsecutiveOnes = true;
                    break;
                }
            }
            if (!foundConsecutiveOnes) {
                result++;
            }
        }
        return result;
    }
 
    static public void Main()
    {
 
        // Code
        int n = 2;
        int m = 12;
        // Function call
        Console.WriteLine(
            "The number of non-negative integers in the range ["
            + n + ", " + m
            + "] whose binary representation does not contain consecutive ones is: "
            + CountNonNegIntegers(n, m));
    }
}
 
// This code is contributed by karthik.


Python3




import math
 
# Function to find the count of non-negative integers which doesn't contain consecutive ones in the given range of Integers.
def countNonNegIntegers(n, m):
    result = 0
    # Iterate through the range of integers from n to m
    for i in range(n, m+1):
        # Convert the integer to a binary string using bitset
        b = format(i, 'b')
        # Check if there are any consecutive ones in the binary string
        if '11' not in b:
            result += 1
    return result
 
# Driver code
n = 2
m = 12
 
# Function call
print("The number of non-negative integers in the range [", n, ", ", m, "] whose binary representation does not contain consecutive ones is: ", countNonNegIntegers(n, m))


Javascript




// JavaScript code for the above approach:
 
// Function to find the count of non-negative integers which doesn't
// contain consecutive ones in the given range of Integers.
function countNonNegIntegers(n, m) {
    let result = 0;
    for (let i = n; i <= m; i++) {
        const b = i.toString(2);
        let foundConsecutiveOnes = false;
        for (let j = 0; j < b.length - 1; j++) {
            if (b[j] === "1" && b[j + 1] === "1") {
                foundConsecutiveOnes = true;
                break;
            }
        }
        if (!foundConsecutiveOnes) result++;
    }
    return result;
}
 
// Driver code
let n = 2;
let m = 12;
 
// Function call
console.log(`The number of non-negative integers in the range [${n}, ${m}] whose binary
representation does not contain consecutive ones is: ${countNonNegIntegers(n, m)}`);


Output

The number of non-negative integers in the range [2, 12] whose binary representation does not contain consecutive ones is: 
6

Time complexity: O(n * 32), where n is the number of integers in the range [n, m]. The reason for this is that the code needs to check each integer in the range and for each integer, it needs to loop through all its bits to see if there are consecutive ones. The number of bits in the binary representation of an integer is limited to 32, so each loop takes O(32) time.
Auxiliary space: O(1), as the code, only uses a constant amount of memory regardless of the size of the input. Memory usage is dominated by the variables “result”, “foundConsecutiveOnes”, “i”, “j”, and the “bitset” object.



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