![]() |
VOOZH | about |
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 8Input: 7
Output: 6
Explanation: Binary representation for 7 is 00...00111 and for 6, it is 00...00110Input: 0
Output:0
Explanation: There is no rightmost set bit
Table of Content
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:
Rightmost unsetBit: 8
Time Complexity:O(log n)
Space Complexity:O(1)
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:
n - 1, which flips all bits from the rightmost set bit onward. n & (n - 1). Rightmost unsetBit: 8
Time Complexity O(1)
Space Complexity: O(1)
Rightmost unsetBit: 8
Time Complexity: O(1)
Auxiliary Space: O(1)