Given N, check if the number is a Fibbinary number or not. Fibbinary numbers are integers whose binary representation includes no consecutive ones.
Examples:
Input : 10
Output : YES
Explanation: 1010 is the binary representation
of 10 which does not contains any
consecutive 1's.
Input : 11
Output : NO
Explanation: 1011 is the binary representation
of 11, which contains consecutive
1's
The idea of doing this is to right shift the number, till n!=0. For every binary representation of 1, check if the last bit found was 1 or not. Get the last bit of binary representation of the integer by doing a(n&1). If the last bit of the binary representation is 1 and the previous bit before doing a right shift was also one, we encounter consecutive 1’s. So we come to the conclusion that it is not a fibbinary number.
Some of the first few Fibbinary numbers are:
0, 2, 4, 8, 10, 16, 18, 20.......
CPP
#include <iostream>
using namespace std;
bool checkFibinnary( int n)
{
int prev_last = 0;
while (n)
{
if ((n & 1) && prev_last)
return false ;
prev_last = n & 1;
n >>= 1;
}
return true ;
}
int main()
{
int n = 10;
if (checkFibinnary(n))
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
|
Java
class GFG {
static boolean checkFibinnary( int n)
{
int prev_last = 0 ;
while (n != 0 )
{
if ((n & 1 ) != 0 && prev_last != 0 )
return false ;
prev_last = n & 1 ;
n >>= 1 ;
}
return true ;
}
public static void main(String[] args)
{
int n = 10 ;
if (checkFibinnary(n) == true )
System.out.println( "YES" );
else
System.out.println( "NO" );
}
}
|
Python3
def checkFibinnary(n):
prev_last = 0
while (n):
if ((n & 1 ) and prev_last):
return False
prev_last = n & 1
n >> = 1
return True
n = 10
if (checkFibinnary(n)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG {
static bool checkFibinnary( int n)
{
int prev_last = 0;
while (n != 0)
{
if ((n & 1) != 0 && prev_last != 0)
return false ;
prev_last = n & 1;
n >>= 1;
}
return true ;
}
public static void Main()
{
int n = 10;
if (checkFibinnary(n) == true )
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
}
|
PHP
<?php
function checkFibinnary( $n )
{
$prev_last = 0;
while ( $n )
{
if (( $n & 1) && $prev_last )
return false;
$prev_last = $n & 1;
$n >>= 1;
}
return true;
}
$n = 10;
if (checkFibinnary( $n ))
echo "YES" ;
else
echo "NO" ;
?>
|
Javascript
<script>
function checkFibinnary(n) {
var prev_last = 0;
while (n != 0) {
if ((n & 1) != 0 && prev_last != 0)
return false ;
prev_last = n & 1;
n >>= 1;
}
return true ;
}
var n = 10;
if (checkFibinnary(n) == true )
document.write( "YES" );
else
document.write( "NO" );
</script>
|
Output:
YES
Time Complexity: O(logN), as we are using a loop to traverse logN times, we are decrementing by floor division of 2 (as right shifting a number by 1 is equivalent to floor division by 2) in each iteration therefore the loop iterates logN times.
Auxiliary Space: O(1), as we are not using any extra space.
Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach