Horje
Set the Left most unset bit

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++

<?php
// php program to set the
// leftmost unset bit
 
// set left most unset bit
function setleftmostunsetbit($n)
{
     
    // if number contain all
    // 1 then return n
    if (($n & ($n + 1)) == 0)
        return $n;
 
    // Find position of leftmost
    // unset bit.
    $pos = 0;
    for ($temp = $n, $count = 0; $temp > 0;
                     $temp >>= 1, $count++)
 
        // if temp L.S.B is zero
        // then unset bit pos is
        // change
        if (($temp & 1) == 0)
            $pos = $count;
 
    // return OR of number
    // and unset bit pos
    return ($n | (1 << ($pos)));
}
 
    // Driver code
    $n = 10;
    echo setleftmostunsetbit($n);
 
//This code is contributed by mits
?>

Javascript

<script>
 
// Javascript program to set the
// leftmost unset bit
 
// Set left most unset bit
function setleftmostunsetbit(n)
{
     
    // If number contain all
    // 1 then return n
    if ((n & (n + 1)) == 0)
        return n;
 
    // Find position of leftmost unset bit.
    let pos = 0;
    for(let temp = n, count = 0; temp > 0;
            temp >>= 1, count++)
 
        // If temp L.S.B is zero
        // then unset bit pos is
        // change
        if ((temp & 1) == 0)
            pos = count;
 
    // Return OR of number and
    // unset bit pos
    return (n | (1 << (pos)));
}
 
// Driver Code
let n = 10;
 
document.write(setleftmostunsetbit(n));
 
// This code is contributed by Manoj.
 
</script>

Output: 

14

Time Complexity: O(log2n)

Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


Bit Magic

Related
Toggle all even bits of a number Toggle all even bits of a number
Toggle first and last bits of a number Toggle first and last bits of a number
Check if actual binary representation of a number is palindrome Check if actual binary representation of a number is palindrome
Reverse actual bits of the given number Reverse actual bits of the given number
Odious number Odious number

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19