VOOZH about

URL: https://www.geeksforgeeks.org/dsa/turn-off-the-rightmost-set-bit/

⇱ Turn off the rightmost set bit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Turn off the rightmost set bit

Last Updated : 26 Apr, 2026

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] Unset the Rightmost Set Bit Using Bitwise Operations - O(log n)Time O(1) Space

The idea is to unset the rightmost set bit of a given number by first identifying its position using bitwise operations. We traverse the bits from right to left using right shift (>>) until we encounter the first set bit (1), which gives the position of the rightmost set bit. Once this position is found, we create a mask using (1 << pos) that has only that bit set. Then, we apply XOR with the original number, which flips that bit from 1 to 0. This effectively unsets the rightmost set bit of the number.

Algorithm:

  • if n == 0, return 0 since there is no set bit to unset.
  • Start from position 0 and check each bit using right shift (n >> pos) and & 1.
  • Move forward until the first set bit (1) is found — this is the rightmost set bit.
  • Create a mask using (1 << pos) to target that bit.
  • apply XOR with the original number to flip that bit from 1 to 0 and return the result.

Output
 Rightmost unsetBit: 8

Time Complexity:O(log n)
Space Complexity:O(1)

[Expected Approach 1] Using n & (n - 1) Trick (Brian Kernighan’s Method) - O(1) Time and O(1) Space

The idea is to unset the rightmost set (1) bit using bit manipulation.When we subtract 1 from a number, all bits from the rightmost set bit (including it) get flipped. By performing a bitwise AND of n and (n - 1), all bits remain unchanged except the rightmost set bit, which becomes 0.

Algorithm:

  • Compute n - 1, which flips all bits from the rightmost set bit onward.
  • Perform bitwise AND operation: n & (n - 1).
  • This keeps all bits before the rightmost set bit unchanged.
  • It turns off (unsets) the rightmost set bit.
  • Return the resulting value.

Output
 Rightmost unsetBit: 8

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

[Expected Approach 2] Using 2’s Complement - O(1) Time and O(1) Space

  • The idea is to find the rightmost set bit using a property of 2's complement arithmetic. When we perform n & (~n + 1) or equivalently n & (-n), we get a number with only the rightmost set bit of n.
  • By subtracting this value from n, we can unset the rightmost set bit.

Output
 Rightmost unsetBit: 8

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

Comment
Article Tags:
Article Tags: