Set the Left most unset bit
Last Updated :
28 May, 2022
Given an integer, set the leftmost unset bit. Leftmost unset bit is the first unset bit after most significant set bit. If all bits (after most significant set bit) are set, then return the number.
Examples:
Input : 10
Output : 14
10 = 1 0 1 0 // 10 binary
14 = 1 1 1 0 // after set left most unset bit
Input : 15
Output : 15
15 = 1 1 1 1 // 15 binary
15 = 1 1 1 1 // because all bits are set
Approach:-
1. Return the number if all bits are set.
2. Traverse all the bit to get the last unset bit.
3. Take OR with the original number and the unset bit.
Below is the implementation of the approach.
C++
#include <iostream>
using namespace std;
int setleftmostunsetbit( int n)
{
if ((n & (n + 1)) == 0)
return n;
int pos = 0;
for ( int temp=n, count=0; temp>0;
temp>>=1, count++)
if ((temp & 1) == 0)
pos = count;
return (n | (1 << (pos)));
}
int main()
{
int n = 10;
cout << setleftmostunsetbit(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int setleftmostunsetbit( int n)
{
if ((n & (n + 1 )) == 0 )
return n;
int pos = 0 ;
for ( int temp = n, count = 0 ; temp > 0 ;
temp >>= 1 , count++)
if ((temp & 1 ) == 0 )
pos = count;
return (n | ( 1 << (pos)));
}
public static void main (String[] args)
{
int n = 10 ;
System.out.println(setleftmostunsetbit(n));
}
}
|
Python3
def setleftmostunsetbit(n):
if not (n & (n + 1 )):
return n
pos, temp, count = 0 , n, 0
while temp:
if not (temp & 1 ):
pos = count
count + = 1 ; temp>> = 1
return (n | ( 1 << (pos)))
n = 10
print (setleftmostunsetbit(n))
|
C#
using System;
class GFG
{
static int setleftmostunsetbit( int n)
{
if ((n & (n + 1)) == 0)
return n;
int pos = 0;
for ( int temp = n, count = 0; temp > 0;
temp >>= 1, count++)
if ((temp & 1) == 0)
pos = count;
return (n | (1 << (pos)));
}
public static void Main ()
{
int n = 10;
Console.WriteLine(setleftmostunsetbit(n));
}
}
|
PHP
<?php
function setleftmostunsetbit( $n )
{
if (( $n & ( $n + 1)) == 0)
return $n ;
$pos = 0;
for ( $temp = $n , $count = 0; $temp > 0;
$temp >>= 1, $count ++)
if (( $temp & 1) == 0)
$pos = $count ;
return ( $n | (1 << ( $pos )));
}
$n = 10;
echo setleftmostunsetbit( $n );
?>
|
Javascript
<script>
function setleftmostunsetbit(n)
{
if ((n & (n + 1)) == 0)
return n;
let pos = 0;
for (let temp = n, count = 0; temp > 0;
temp >>= 1, count++)
if ((temp & 1) == 0)
pos = count;
return (n | (1 << (pos)));
}
let n = 10;
document.write(setleftmostunsetbit(n));
</script>
|
Output:
14
Time Complexity: O(log2n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...