Given a number n
and a value k
, turn off the kth bit in n
. Here, k = 1 refers to the right-most bit of n
.
Example 1:
Example 2:
The solution here is simple, and only a single line is needed for it: n & ~(1 << (k - 1))
.
Let’s break down the expression given above:
&
, ~
, and <<
operators.1 << (k - 1)
: Here, we generate a mask number using the left-shift operator. This is equivalent to 2(k-1). Then, we generate a number where the kth bit is set.~(1 << (k - 1))
: We apply the “NOT” operator where we invert all the bits. Now, the kth bit will be unset unlike all the other bits.n & ~(1 << (k - 1))
: We perform an “AND” (&
) operation on the result that comes from step 3 and n
where the kth bit is. This results in us turning off the kth (zero bit from the previous step) bit as we perform an “AND” operation with n
.Let’s look at an example of this:
k - 1
- (3 - 1) = 21 << (k - 1)
- (1 << (3 - 1)) = (1 << 2) = 4 (000…0100)~(1 << (k - 1))
- (~4) = -5 (111…1011)n & ~(1 << (k - 1))
- (7 & (-5)) = (000…0111 & 111…1011) = 3 (000…011)Note:
...
is used to indicate a 32-bit binary representation.
public class Main {static int turnOffKthBit(int n, int k) {return n & ~(1 << (k - 1));}public static void main(String[] args) {int n = 7;int k = 3;System.out.println(String.format("KthBitTurnOff(%s, %s) = %s", n, k, turnOffKthBit(n , k)));}}