Get the position of rightmost unset bit
Last Updated :
22 Jun, 2022
Given a non-negative number n. Find the position of rightmost unset bit in the binary representation of n, considering the last bit at position 1, 2nd last bit at position 2 and so on. If no 0’s are there in the binary representation of n. then print “-1”.
Examples:
Input : n = 9
Output : 2
(9)10 = (1001)2
The position of rightmost unset bit in the binary
representation of 9 is 2.
Input : n = 32
Output : 1
Approach: Following are the steps:
- If n = 0, return 1.
- If all bits of n are set, return -1. Refer this post.
- Else perform bitwise not on the given number(operation equivalent to 1’s complement). Let it be num = ~n.
- Get the position of rightmost set bit of num. This will be the position of rightmost unset bit of n.
C++
#include <bits/stdc++.h>
using namespace std;
int getPosOfRightmostSetBit( int n)
{
return log2(n&-n)+1;
}
int getPosOfRightMostUnsetBit( int n)
{
if (n == 0)
return 1;
if ((n & (n + 1)) == 0)
return -1;
return getPosOfRightmostSetBit(~n);
}
int main()
{
int n = 9;
cout << getPosOfRightMostUnsetBit(n);
return 0;
}
|
Java
class GFG {
static int getPosOfRightmostSetBit( int n)
{
return ( int )((Math.log10(n & -n)) / Math.log10( 2 )) + 1 ;
}
static int getPosOfRightMostUnsetBit( int n) {
if (n == 0 )
return 1 ;
if ((n & (n + 1 )) == 0 )
return - 1 ;
return getPosOfRightmostSetBit(~n);
}
public static void main(String arg[])
{
int n = 9 ;
System.out.print(getPosOfRightMostUnsetBit(n));
}
}
|
Python3
import math as m
def getPosOfRightmostSetBit(n):
return (m.log(((n & - n) + 1 ), 2 ))
def getPosOfRightMostUnsetBit(n):
if (n = = 0 ):
return 1
if ((n & (n + 1 )) = = 0 ):
return - 1
return getPosOfRightmostSetBit(~n)
n = 13 ;
ans = getPosOfRightMostUnsetBit(n)
print ( round (ans))
|
C#
using System;
class GFG
{
static int getPosOfRightmostSetBit( int n)
{
return ( int )((Math.Log10(n & -n)) / Math.Log10(2)) + 1;
}
static int getPosOfRightMostUnsetBit( int n) {
if (n == 0)
return 1;
if ((n & (n + 1)) == 0)
return -1;
return getPosOfRightmostSetBit(~n);
}
public static void Main()
{
int n = 9;
Console.Write(getPosOfRightMostUnsetBit(n));
}
}
|
PHP
<?php
function getPosOfRightmostSetBit( $n )
{
return ceil (log( $n &- $n ) + 1);
}
function getPosOfRightMostUnsetBit( $n )
{
if ( $n == 0)
return 1;
if (( $n & ( $n + 1)) == 0)
return -1;
return getPosOfRightmostSetBit(~ $n );
}
$n = 9;
echo getPosOfRightMostUnsetBit( $n );
?>
|
Javascript
<script>
function getPosOfRightmostSetBit(n)
{
return Math.log2(n&-n)+1;
}
function getPosOfRightMostUnsetBit(n)
{
if (n == 0)
return 1;
if ((n & (n + 1)) == 0)
return -1;
return getPosOfRightmostSetBit(~n);
}
let n = 9;
document.write(getPosOfRightMostUnsetBit(n));
</script>
|
Output:
2
Time Complexity – O(1)
Space Complexity – O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...