Given a positive integer n. The problem is to check whether only the first and last bits are set in the binary representation of n.
Examples:
Input : 9
Output : Yes
(9)10 = (1001)2, only the first and
last bits are set.
Input : 15
Output : No
(15)10 = (1111)2, except first and last
there are other bits also which are set.
Approach: Following are the steps:
- If n == 1, return “Yes”.
- Else check whether n-1 is a power of 2. Refer this post.
C++
#include <bits/stdc++.h>
using namespace std;
bool powerOfTwo(unsigned int n)
{
return (!(n & n-1));
}
bool onlyFirstAndLastAreSet(unsigned int n)
{
if (n == 1)
return true ;
if (n == 2)
return false ;
return powerOfTwo(n-1);
}
int main()
{
unsigned int n = 9;
if (onlyFirstAndLastAreSet(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean powerOfTwo( int n)
{
return ((n & n - 1 ) == 0 );
}
static boolean onlyFirstAndLastAreSet( int n)
{
if (n == 1 )
return true ;
return powerOfTwo(n- 1 );
}
public static void main (String[] args) {
int n = Integer.parseUnsignedInt( "9" );
if (onlyFirstAndLastAreSet(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def powerOfTwo (n):
return ( not (n & n - 1 ))
def onlyFirstAndLastAreSet (n):
if (n = = 1 ):
return True
return powerOfTwo (n - 1 )
n = 9
if (onlyFirstAndLastAreSet (n)):
print ( 'Yes' )
else :
print ( 'No' )
|
C#
using System;
class GFG {
static bool powerOfTwo( uint n)
{
return ((n & n - 1) == 0);
}
static bool onlyFirstAndLastAreSet( uint n)
{
if (n == 1)
return true ;
return powerOfTwo(n - 1);
}
public static void Main()
{
uint n = ( uint )9;
if (onlyFirstAndLastAreSet(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function powerOfTwo( $n )
{
return (!( $n & $n - 1));
}
function onlyFirstAndLastAreSet( $n )
{
if ( $n == 1)
return true;
if ( $n == 2)
return false;
return powerOfTwo( $n - 1);
}
$n = 9;
if (onlyFirstAndLastAreSet( $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function powerOfTwo(n)
{
return (!(n & n-1));
}
function onlyFirstAndLastAreSet(n)
{
if (n == 1)
return true ;
if (n == 2)
return false ;
return powerOfTwo(n-1);
}
var n = 9;
if (onlyFirstAndLastAreSet(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity – O(1)
Space Complexity – O(1)
This article is contributed by Ayush Jauhari. 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.