Turn off the rightmost set bit

08 Jul, 2022
Write a program that unsets the rightmost set bit of an integer. Examples :  
Input:  12 (00...01100)
Output: 8 (00...01000)

Input:  7 (00...00111)
Output: 6 (00...00110)
 
Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit (including the set bit). So, doing n&(n-1) would give us the required result. 
So, now let us see how n – 1 is flipping all the bits to the right (including the rightmost set bit also) of the n. Taking n = 12, so (n – 1) = 11,  
n can be written like (n = (n – 1) + 1), so now we can think of this problem as Adding 1 to Any Number (refer this article for better understanding)Binary representation of (n-1) = 11 = 1011, so now lets make n from (n-1), which can be done by adding a 1 to (n-1)On adding 1 to any number X, all bits to the right of  rightmost 0 (including the rightmost zero) gets flipped(n-1) = 1011 
(n-1) + 1 = 1100 (all the bits to the right of rightmost zero (including rightmost zero) got flipped)Since we have flipped the rightmost zero, so now, rightmost zero is now flipped to rightmost 1 (aka the rightmost set bit of n) and all bits before rightmost 0 are the same as beforeX = 010 . . . . . 0 (rightmost zero) 111
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
X + 1 = 010 . . . . . 1 (rightmost one) 0 0 0
Example : 
X = 71 = Think of it as n – 1 
Binary Representation of X = 1000111
X + 1 = 72 = Think of it as n 
Binary Representation of (X+1) = 1001000Observation : 
1. All the bits to the left of rightmost 0 (excluding rightmost 0) in X (thinking it as n – 1) are same as in to the left of the rightmost 1(excluding rightmost 1)  in X + 1 (thinking of it as n)
2. All the bits to the right of rightmost 0 (including rightmost 0) in X (thinking it as n – 1) are different as in to the right of the rightmost 1 (including rightmost 1) in X + 1 (thinking of it as n)
So bitwise AND of left part of X (till rightmost 0, excluding rightmost 0) and left part of X + 1 (till rightmost 1, excluding rightmost 1) will give the required answer,  bitwise AND right part of X (from rightmost 0) and right part of X + 1 (from rightmost 1 (rightmost set bit)) will result in 0  
C++
C
Java
Python3
C#
Javascript
PHP
#include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){    return n & (n - 1);} // Driver Codeint main(){    int n = 7;    cout<<"The number after unsetting the";    cout<<" rightmost set bit "<<fun(n);    return 0;}   //This code is contributed by rathbhupendra
#include <stdio.h> // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){    return n & (n - 1);} // Driver Codeint main(){    int n = 7;    printf("The number after unsetting the");    printf(" rightmost set bit %d", fun(n));    return 0;}
// Java program to unset the// rightmost set bit of an integer. class GFG {     /* unsets the rightmost set bit     of n and returns the result */    static int fun(int n)    {        return n & (n - 1);    }     // Driver code    public static void main(String arg[])    {        int n = 7;        System.out.print("The number after unsetting "                         + "the rightmost set bit " + fun(n));    }} // This code is contributed by Anant Agarwal.
# unsets the rightmost set bit# of n and returns the resultdef fun(n):      return n & (n-1) # Driver code n = 7print("The number after unsetting the rightmost set bit", fun(n)) # This code is contributed# by Anant Agarwal.
// C# program to unset the// rightmost set bit of an integer.using System; class GFG {     /* unsets the rightmost set bit    of n and returns the result */    static int fun(int n)    {        return n & (n - 1);    }     // Driver code    public static void Main()    {        int n = 7;        Console.Write("The number after unsetting "                      + "the rightmost set bit " + fun(n));    }} // This code is contributed by Sam007
<script>// JavaScript program for the above approach  /* unsets the rightmost set bit    of n and returns the result */    function fun(n)    {        return n & (n - 1);    } // Driver Code    let n = 7;    document.write("The number after unsetting "                + "the rightmost set bit " + fun(n)); // This code is contributed by susmitakundugoaldanga.</script>
<?php// unsets the rightmost set bit// of n and returns the resultfunction fun($n){return $n & ($n - 1);} // Driver Code$n = 7;echo "The number after unsetting the".     " rightmost set bit ", fun($n); // This code is contributed by vt_m. ?>
The number after unsetting the rightmost set bit 6
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Approach:
The rightmost set bit can be switched off by subtracting the LSB from the number.
The LSB of a number can be obtained using (n & (-n)), therefore the number with the rightmost set bit of n switched off is equal to n – (n & (-n));
C++
Java
Python3
C#
Javascript
//C++ program to implement the approach #include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){    return  n - (n & (-n));} // Driver Codeint main(){    int n = 7;    cout<<"The number after unsetting the";    cout<<" rightmost set bit: "<<fun(n);    return 0;}   //This code is contributed by phasing17
// Java program to implement the approachclass GFG{   // unsets the rightmost set bit  // of n and returns the result  static int fun(int n)  {    return n - (n & (-n));  }   // Driver Code  public static void main(String[] args)  {    int n = 7;    System.out.print("The number after unsetting the");    System.out.print(" rightmost set bit: " + fun(n));  }} // This code is contributed by phasing17
# Python3 program to implement the approach # unsets the rightmost set bit# of n and returns the resultdef fun(n):    return n - (n & (-n)) # Driver Coden = 7print("The number after unsetting the rightmost set bit:", fun(n)) # This code is contributed by phasing17
// C# program to implement the approachusing System; class GFG {   // unsets the rightmost set bit  // of n and returns the result  static int fun(int n) { return n - (n & (-n)); }   // Driver Code  public static void Main(string[] args)  {    int n = 7;    Console.Write("The number after unsetting the");    Console.Write(" rightmost set bit: " + fun(n));  }} // This code is contributed by phasing17
// JavaScript program to implement the approach // unsets the rightmost set bit// of n and returns the resultfunction fun(n){    return  n - (n & (-n));} // Driver Codelet n = 7;console.log("The number after unsetting the rightmost set bit:", fun(n)); // This code is contributed by phasing17
The number after unsetting the rightmost set bit: 6
Time Complexity: O(1)
Auxiliary Space: O(1)
 
Turn off the rightmost set bit | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersTurn off the rightmost set bit | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=QKUh9hHqL4w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem 
vt_m
rathbhupendra
susmitakundugoaldanga
anshkush92
souravmahato348
phasing17
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.