Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach
Last Updated :
15 Jun, 2022
Given a positive integer n. The problem is to check if the number is Fibbinary Number or not. Fibbinary numbers are integers whose binary representation contains 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.
Approach: If (n & (n >> 1)) == 0, then ‘n’ is a fibbinary number Else not.
C++
#include <bits/stdc++.h>
using namespace std;
bool isFibbinaryNum(unsigned int n) {
if ((n & (n >> 1)) == 0)
return true ;
return false ;
}
int main() {
unsigned int n = 10;
if (isFibbinaryNum(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG {
static boolean isFibbinaryNum( int n) {
if ((n & (n >> 1 )) == 0 )
return true ;
return false ;
}
public static void main(String[] args) {
int n = 10 ;
if (isFibbinaryNum(n) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isFibbinaryNum( n):
if ((n & (n >> 1 )) = = 0 ):
return 1
return 0
n = 10
if (isFibbinaryNum(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isFibbinaryNum( int n) {
if ((n & (n >> 1)) == 0)
return true ;
return false ;
}
public static void Main() {
int n = 10;
if (isFibbinaryNum(n) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function isFibbinaryNum( $n )
{
if (( $n & ( $n >> 1)) == 0)
return true;
return false;
}
$n = 10;
if (isFibbinaryNum( $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isFibbinaryNum(n) {
if ((n & (n >> 1)) == 0)
return true ;
return false ;
}
let n = 10;
if (isFibbinaryNum(n) == true )
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output :
Yes
Time Complexity: O(1).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...