# Bitwise Algorithm 1: Clear Bit

### Problem

Given an integer , clear the th bit from the right (the rightmost bit is the 0th bit).

For example, let's say . Here the st, nd, rd, th, and th bit are set. So for , the algorithm should return , but for , since the th bit is already clear, it should return the original value unchanged.

### Algorithm

To solve this problem we need to do some bit masking. We want to mask one bit to 0, while leaving the other bits unchanged. To mask a bit to 0, we use a bitwise AND. We need to bitwise AND the integer with a number containing bits all set to 1, except in the kth location set to 0. In boolean algebra whereas , so we leave all the bits unchanged except in the th location we clear it.

For example if and , we want to do the operation , which gives us our answer, .

The question then is how do we compute the number where all bits are set except the th bit. To do this, we can take the number 1 shift it to the left by positions and negate the result.

Here is the code in java:

public static int clearBit(int x, int k) { return x & ~(1 << k); }