![]() |
VOOZH | about |
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 Output: 15
The idea is to use bitwise <<, & and ~ operators. Using the expression "~(1 << (k - 1))", we get a number that has all bits set, except the kth bit. If we do bitwise & of this expression with n, we get a number that has all bits the same as n except the kth bit which is 0.
Below is the implementation of the above idea.
7
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2: Using XOR operator.
Left shift 1 by (k - 1) times and check if kth bit is set or not, if set then take XOR for togging the kth bit.
Below is the implementation of the above approach:
7
Time Complexity: O(1)
Auxiliary Space: O(1)
Exercise: Write a function turnOnK() that turns the k'th bit on.