How can we turn off a kth bit in a number?

Overview

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:

  • Input: n = 14, k = 1
  • Output: 14

Example 2:

  • Input: n = 7, k = 2
  • Output: 5

Solution

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:

  1. We use the &, ~, and << operators.
  2. 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.
  3. ~(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.
  4. 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:

  • n = 7, k = 3
  • k - 1 - (3 - 1) = 2
  • 1 << (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.

Code

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)));
}
}

Free Resources