1 to n bit numbers with no consecutive 1s in binary representation
Last Updated :
03 Apr, 2023
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)
Share your thoughts in the comments
Please Login to comment...