Clear the K-th Bit
Given a number n
and an integer i
, clear the K
th bit of n
. Meaning, set the K
th bit of n
to 0
.
Example
Input: n = 5, K = 2
Output: 1
Explanation: 5 in binary is 101.
Clearing the 2nd bit will result in 001 which is 1 in decimal.
Approach
- We know how to set the bit
k-th
position, with the help left shift and OR operator. - Now we can do ~(i << k) and then AND it with n to clear the
k-th
bit.
❤️🔥
So the formula to clear the k-th
bit is: N & (~(1 << K))
Code
clear-kth-bit.cpp
int clearKthBit(int n, int k) {
return n & (~(1 << k));
}
Dry Run
Let's dry run the code with the given example:
n = 5, K = 2
n
in binary is101
.1 << K
will be1 << 2
which is100
.~(1 << K)
will be~100
which is011
.~100
is011
because~1
is0
and~0
is1
(Not operator).
n & (~(1 << K))
will be101 & 011
which is001
.001
in decimal is1
.
So, the output is 1
.
Complexity Analysis
🔥
Time Complexity: O(1) | Space Complexity: O(1)