Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.
Examples:
Input: N = 4
Output: 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.
Input: n = 3
Output: 1 2 4 5
Approach:
- There will be 2n numbers with number of bits from 1 to n.
- Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise and of current number i and left-shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then the given number contains consecutive set bits.
Below is the implementation of the above approach:
C++
#include<iostream>
using namespace std;
void printNonConsecutive( int n)
{
int p = (1 << n);
for ( int i = 1; i < p; i++)
if ((i & (i << 1)) == 0)
cout << i << " " ;
}
int main()
{
int n = 3;
printNonConsecutive(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void printNonConsecutive( int n)
{
int p = ( 1 << n);
for ( int i = 1 ; i < p; i++)
if ((i & (i << 1 )) == 0 )
System.out.print(i + " " );
}
public static void main(String[] args)
{
int n = 3 ;
printNonConsecutive(n);
}
}
|
Python3
def printNonConsecutive(n):
p = ( 1 << n)
for i in range ( 1 , p):
if ((i & (i << 1 )) = = 0 ):
print (i, end = " " )
n = 3
printNonConsecutive(n)
|
C#
using System;
class GFG
{
static void printNonConsecutive( int n)
{
int p = (1 << n);
for ( int i = 1; i < p; i++)
if ((i & (i << 1)) == 0)
Console.Write(i + " " );
}
public static void Main()
{
int n = 3;
printNonConsecutive(n);
}
}
|
PHP
<?php
function printNonConsecutive( $n )
{
$p = (1 << $n );
for ( $i = 1; $i < $p ; $i ++)
if (( $i & ( $i << 1)) == 0)
echo $i . " " ;
}
$n = 3;
printNonConsecutive( $n );
?>
|
Javascript
<script>
function printNonConsecutive(n)
{
let p = (1 << n);
for (let i = 1; i < p; i++)
if ((i & (i << 1)) == 0)
document.write(i + " " );
}
let n = 3;
printNonConsecutive(n);
</script>
|
Time Complexity: O(2N)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
03 Apr, 2023
Like Article
Save Article