The Wayback Machine - https://web.archive.org/web/20240930205822/https://www.geeksforgeeks.org/turn-off-the-rightmost-set-bit/
Open In App

Turn off the rightmost set bit

Last Updated : 14 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer n, turn remove turn off the rightmost set bit in it. 

Input: 12
Output: 8
Explanation : Binary representation of 12 is 00…01100. If we turn of the rightmost set bit, we get 00…01000 which is binary representation of 8

Input: 7
Output: 6
Explanation : Binary representation for 7 is 00…00111 and for 6, it is 00…00110

Input: 0
Output: 0
Explanation : There is no rightmost set bit

Naive Approach

  • A simple is to find the position of the rightmost set bit in the number by a bitwise right shift operation to check for the first occurrence of 1.  
  • Then, flip the bit in this position. Flipping can be done by applying XOR of the given number and the number with the bit in this position set.
    0 ^ 1 = 1 1 ^ 1 = 0 Xor with 1 flips the bit.
  • Setting only a given bit can be done by taking 2 to the power of position to set a particular bit. 

Below is the implementation of the above approach. 

C++
// C++ program to unset the rightmost
// set bit
#include <bits/stdc++.h>
using namespace std;

// Unsets the rightmost set bit
// of n and returns the result
int unsetLSB(int n)
{
    if (n == 0)
        return 0;
  
    // Find the rightmost set bit
    int pos = 0;
    while ((n >> pos) & 1 == 0) {
        pos++;
    }
  
    // Unset the rightmost set bit
    n = n ^ (1 << pos);
  
    return n;
}

// Driver code
int main()
{
    int n = 12;
    cout << unsetLSB(n);
    return 0;
}
C
#include <stdio.h>

// Unsets the rightmost set pos
// of n and returns the result
int unsetLSB(int n) {
    if (n == 0)
        return 0;
  
    // Find the rightmost set pos
    int pos = 0;
    while ((n >> pos) & 1 == 0) {
        pos++;
    }
  
    // Unset the rightmost set pos
    n = n ^ (1 << pos);
  
    return n;
}

// Driver code
int main() {
    int n = 12;
    printf("%d\n", unsetLSB(n));
    return 0;
}
Java
public class GfG {

    // Unsets the rightmost set pos
    // of n and returns the result
    public static int unsetLSB(int n) {
        if (n == 0)
            return 0;
      
        // Find the rightmost set pos
        int pos = 0;
        while ((n >> pos & 1) == 0) {
            pos++;
        }
      
        // Unset the rightmost set pos
        n = n ^ (1 << pos);
      
        return n;
    }

    // Driver code
    public static void main(String[] args) {
        int n = 12;
        System.out.println(unsetLSB(n));
    }
}
Python
# Unsets the rightmost set pos
# of n and returns the result
def unset_lsb(n):
    if n == 0:
        return 0
    
    # Find the rightmost set pos
    pos = 0
    while (n >> pos) & 1 == 0:
        pos += 1
    
    # Unset the rightmost set pos
    n = n ^ (1 << pos)
    
    return n

# Driver code
n = 12
print(unset_lsb(n))
CSharp
using System;

public class GfG {

    // Unsets the rightmost set pos
    // of n and returns the result
    public static int UnsetLSB(int n) {
        if (n == 0)
            return 0;
      
        // Find the rightmost set pos
        int pos = 0;
        while ((n >> pos & 1) == 0) {
            pos++;
        }
      
        // Unset the rightmost set pos
        n = n ^ (1 << pos);
      
        return n;
    }

    // Driver code
    public static void Main() {
        int n = 12;
        Console.WriteLine(UnsetLSB(n));
    }
}
JavaScript
// Unsets the rightmost set pos
// of n and returns the result
function unsetLSB(n) {
    if (n === 0)
        return 0;

    // Find the rightmost set pos
    let pos = 0;
    while ((n >> pos & 1) === 0) {
        pos++;
    }
    
    // Unset the rightmost set pos
    n = n ^ (1 << pos);
    
    return n;
}

// Driver code
let n = 12;
console.log(unsetLSB(n));

Output
8

Time Complexity:  O(Position of the Rightmost Set Bit)
Auxiliary Space: O(1)

Expected Approach 1 – Subtracting by One

We mainly need keep all other bits as it is and turn off the last set bit. Below are the main two we use.

1) Compute (n-1) : When we subtract a number by 1, all bits after the rightmost set bit (including it) are toggled. For example : 
10 in binary is 00001010 and 9 in binary is 00001001 
8 in binary is 00001000 and 7 in binary is 00000111 

2) Do Bitwise AND of n and (n-1) : If we do bitwise and of n and n-1, the result bits before the rightmost set bit remain as it (because these bits were not changed in -1) is and the bits after it also remain as it is (because these bits were 0 in n and became 1 in n-1). The only bit that changes is the rightmost set bit (It was 1 in n and became 0 in n-1).

So we get the required result after n & (n – 1)
For example, bitwise and of 10 and 9 gives us 8 ( 00001000 ) and bitwsie and of 8 and 7 gives us 0 (00000000)

This idea is used in Brian Kernighan’s Algorithm for efficiently computing count of set bits.

C++
#include <bits/stdc++.h>
using namespace std;

// unsets the rightmost set bit 
// of n and returns the result 
int unsetLSB(int n) 
{ 
    return (n & (n - 1)); 
} 

// Driver Code 
int main() 
{ 
    int n = 7; 
    cout << unsetLSB(n); 
    return 0; 
} 
C
#include <stdio.h>

// unsets the rightmost set bit 
// of n and returns the result 
unsigned int unsetLSB(unsigned int n) {
    return (n & (n - 1));
}

// Driver Code 
int main() {
    unsigned int n = 7;
    printf("%u\n", unsetLSB(n));
    return 0;
}
Java
public class GfG {

    // unsets the rightmost set bit 
    // of n and returns the result 
    public static int unsetLSB(int n) {
        return (n & (n - 1));
    }

    // Driver Code 
    public static void main(String[] args) {
        int n = 7;
        System.out.println(unsetLSB(n));
    }
}
Python
# unsets the rightmost set bit 
# of n and returns the result 
def unset_lsb(n):
    return n & (n - 1)

# Driver Code 
n = 7
print(unset_lsb(n))
C#
using System;

public class GfG {

    // unsets the rightmost set bit 
    // of n and returns the result 
    public static uint UnsetLSB(uint n) {
        return n & (n - 1);
    }

    // Driver Code 
    public static void Main() {
        uint n = 7;
        Console.WriteLine(UnsetLSB(n));
    }
}
JavaScript
// unsets the rightmost set bit 
// of n and returns the result 
function unsetLSB(n) {
    return n & (n - 1);
}

// Driver Code 
let n = 7;
console.log(unsetLSB(n));

Output
6

Time Complexity: O(1)
Auxiliary Space: O(1)

Expected Approach 2 – Using 2’s Complement

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)). When we make a number negative, we get two’s complement of the number (this is machine dependent, but most of the machines use 2’s complement only). Please refer Unset the rightmost set bit using 2s complement for details
 



Previous Article
Next Article

Similar Reads

Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Set the rightmost off bit
Write a program that sets the rightmost 0 bit of an integer. Examples : Input: 12 (00...01100) Output: 13 (00...01101) Input: 7 (00...00111) Output: 15 (00...01111) If we add 1 to a number, all set bits after rightmost unset (or zero bit) become 0 and the rightmost unset bit becomes 1. C/C++ Code // CPP program to set the rightmost unset bit #inclu
3 min read
How to turn off a particular bit in a number?
Given a number n and a value k, turn off the kth bit in n. Please note that k = 1 means the rightmost bit. Examples: Input: n = 15, k = 1 Output: 14 Input: n = 14, k = 1 Output: 14 The rightmost bit was already off, so no change. Input: n = 15, k = 2 Output: 13 Input: n = 15, k = 3 Output: 11 Input: n = 15, k = 4 Output: 7 Input: n = 15, k >= 5
7 min read
Rank the array according to rightmost set bit and least set bits
Given an array arr[] of N integers, the task is to replace each element of Array with their rank according to Rightmost-Set Bit (RSB) in descending manner, If the RSB is the same for two numbers then choose the one which has the least number of set bits if the set bits of two numbers are same then choose the number who comes first in the array. Exa
10 min read
Predict the winner of a game by converting 0 to 1 turn by turn following the given rules
Given a binary string str consisting of only 0 and 1, where 0 represent an unoccupied position and 1 represent an occupied position. Two players A and B have to occupy an unoccupied position (convert 0 to 1) turn by turn following the given rules: The player can only occupy the unoccupied positionThe player can only move to its adjacent position in
10 min read
Number formed by the rightmost set bit in N
Given an integer N, the task is to find an integer M formed by taking the rightmost set bit in N i.e. the only set bit in M will be the rightmost set bit in N and the rest of the bits will be unset.Examples: Input: N = 7 Output: 1 7 = 111, the number formed by the last set bit is 001 i.e. 1.Input: N = 10 Output: 2 10 = 1010 -> 0010 = 2Input: N =
4 min read
Number formed by flipping all bits to the left of rightmost set bit
Given an integer N, the task is to flip all the bits to the left of rightmost set bit and print the number generated. Examples: Input: N = 10 Output: 6 Explanation: 10 (1010 in binary) flipping all bits left to rightmost set bit (index 2) -> 6 (0110 in binary) Input: N = 120 Output: 8 Explanation: 120 (1111000 in binary) flipping all bits left t
8 min read
Count numbers up to N whose rightmost set bit is K
Given two positive integers N and K, the task is to count the numbers from the range [1, N] whose Kth bit from the right, i.e. LSB, is the rightmost set bit. Examples: Input: N = 15, K = 2Output: 4Explanation:(2)10 = (010)2, (6)10 = (110)2, (10)10 = (1010)2, (14)10 = (1110)2 have the 2nd bit from the right is set. Input: N = 10 K = 3Output: 3 Naive
5 min read
Set the rightmost unset bit
Given a non-negative number n. The problem is to set the rightmost unset bit in the binary representation of nExamples: Input : 21Output : 23(21)10 = (10101)2Rightmost unset bit is at position 2(from right) as highlighted in the binary representation of 21.(23)10 = (10111)2The bit at position 2 has been set.Input : 2Output : 3One method is discusse
6 min read
Position of rightmost set bit
Write a one-line function to return the position of the first 1 from right to left, in the binary representation of an Integer. Examples: Input: n = 18Output: 2Explanation: Binary Representation of 18 is 010010, hence position of first set bit from right is 2. Input: n = 19Output: 1Explanation: Binary Representation of 19 is 010011, hence position
15 min read
Set the rightmost unset bit
Given a non-negative number n. The problem is to set the rightmost unset bit in the binary representation of n. If there are no unset bits, then just leave the number as it is. Examples: Input : 21 Output : 23 (21)10 = (10101)2 Rightmost unset bit is at position 2(from right) as highlighted in the binary representation of 21. (23)10 = (10111)2 The
10 min read
Unset he rightmost set bit using 2s complement
Given The task is to unset the rightmost set bit of N.Examples: Input: N = 5 Output: 4Explanation:101(5) -> 100(4)Input : N = 78Output : 76Explanation:1001110(78) -> 1001100(76)We have discussed Different Approaches Unset the LSB. In this post, we are going to discuss a new approach using two's complement. Obtain 2's complement of the number
3 min read
Position of rightmost bit with first carry in sum of two binary
Given two non-negative integers a and b. The problem is to find the position of the rightmost bit where a carry is generated in the binary addition of a and b. Examples: Input : a = 10, b = 2 Output : 2 (10)10 = (1010)2 (2)10 = (10)2. 1010 + 10 As highlighted, 1st carry bit from the right will be generated at position '2'. Input : a = 10, b = 5 Out
4 min read
Position of rightmost different bit
Given two numbers m and n. Find the position of the rightmost different bit in the binary representation of numbers. It is guaranteed that such a bit exists Examples: Input: m = 11, n = 9Output: 2Explanation: (11)10 = (1011)2(9)10 = (1001)2It can be seen that 2nd bit from the right is different Input: m = 52, n = 4Output: 5Explanation: (52)10 = (11
8 min read
Get the position of rightmost unset bit
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
5 min read
Position of rightmost common bit in two numbers
Given two non-negative numbers m and n. Find the position of rightmost same bit in the binary representation of the numbers. Examples: Input : m = 10, n = 9 Output : 3 (10)10 = (1010)2 (9)10 = (1001)2 It can be seen that the 3rd bit from the right is same. Input : m = 16, n = 7 Output : 4 (16)10 = (10000)2 (7)10 = (111)2, can also be written as = (
9 min read
How to turn on a particular bit in a number?
Given a number n and a value k, turn on the k’th bit in n.Examples: Input: n = 4, k = 2 Output: 6 Input: n = 3, k = 3 Output: 7 Input: n = 64, k = 4 Output: 72 Input: n = 64, k = 5 Output: 80 The idea is to use bitwise << and | operators. Using expression "(1 << (k – 1))“, we get a number which has all bits unset, except the k’th bit. I
4 min read
Find the index at which bit must be set to maximise distance between next set bit
Given a binary array arr[]. The task is to find the position of any 0 in arr[] such that the distance between two set bits is maximized. Examples Input: arr = [1, 0, 0, 0, 1, 0, 1]Output: 2Explanation: Flip the bit at arr[2] Input: arr = [1, 0, 0, 0]Output: 3 Approach: The problem can be solved by finding the longest distance between adjacent set b
5 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count bases which contains a set bit as the Most Significant Bit in the representation of N
Given a positive integer N, the task is to count the number of different bases in which, when N is represented, the most significant bit of N is a found to be a set bit. Examples: Input: N = 6Output: 4Explanation: The number 6 can be represented in 5 different bases, i.e. base 2, base 3, base 4, base 5, base 6. (6)10 in base 2: (110)2(6)10 in base
5 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Implementation of Bit Stuffing and Bit Destuffing
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1's. Given an array, arr[] of size N consisting of 0's and 1's, the task is to return an array after the bit stuffing. Examples: Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecut
15 min read
Find X in range [1, N] of bit size A[i] such that X^2's bit size is not present in Array
Given an array A of N integers, where: Each element of array represents the bit size of an imaginary unsigned integer datatype.If ith imaginary datatype has a size of A[i] bits, then it can store integers from size 0 to 2A[i]-1. The task is to check if there exist some integer X, such that: X is in range 1 to NX can fit in a datatype of bit size A[
8 min read
Minimize bit flips such that each continuous segment of same bit has even length
Given a binary string S of even size that contains only 0s and 1s, the task is to find the minimum flips (that is 0 to 1 or 1 to 0) such that every contiguous subsegment that contains the same bit is of even size. Examples: Input: S = "1110011000 "Output: 3Explanation: Change S[2], S[5] and S[6] to '0'. After that S becomes "1100000000", it can be
8 min read
Inserting m into n such that m starts at bit j and ends at bit i.
We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully f
8 min read
Leftmost and rightmost indices of the maximum and the minimum element of an array
Given an array arr[], the task is to find the leftmost and the rightmost indices of the minimum and the maximum element from the array where arr[] consists of non-distinct elements.Examples: Input: arr[] = {2, 1, 1, 2, 1, 5, 6, 5} Output: Minimum left : 1 Minimum right : 4 Maximum left : 6 Maximum right : 6 Minimum element is 1 which is present at
15+ min read
Find Leftmost and Rightmost node of BST from its given preorder traversal
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes. Examples: Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 } Output : Leftmost = 1, Rightmost = 5 The BST constructed from this preorder sequence would be: 3 / \ 2 5 / / 1 4 Leftmost Node of this tree is equal to 1 Rightmost Node of this t
5 min read
Print all nodes except rightmost node of every level of the Binary Tree
Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3 \ \ 4 5 Output: 2 4 Approach: To print nodes leve
7 min read
Print leftmost and rightmost nodes of a Binary Tree
Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost. For example, the output for the following is 15, 10, 20, 8, 25. Recommended PracticeLeftmost and rightmost nodes of binary treeTry It! A Simple Solution is to do two traversals using the approaches discussed for printing left view and
7 min read
Find the winner of a game of removing at most 3 stones from a pile in each turn
Given an array arr[] of size N, denoting values assigned to N stones, two players, Player1 and Player2, play a game of alternating turns. In each turn, a player can take 1, 2, or 3 stones from the first remaining stones with the sum of values of all the removed stones added to the player's score. Considering that both players play optimally, the ta
15+ min read
Article Tags :
Practice Tags :