Difficulty Level: Rookie

Given a number n and a value k, turn of the k’th bit in n.

Examples:

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

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 expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k’th bit which is 0.

[ad type=”banner”]

Following is C++ implementation of this.

[pastacode lang=”cpp” manual=”%23include%20%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F%2F%20Returns%20a%20number%20that%20has%20all%20bits%20same%20as%20n%0A%2F%2F%20except%20the%20k’th%20bit%20which%20is%20made%200%0Aint%20turnOffK(int%20n%2C%20int%20k)%0A%7B%0A%20%20%20%20%2F%2F%20k%20must%20be%20greater%20than%200%0A%20%20%20%20if%20(k%20%3C%3D%200)%20return%20n%3B%0A%20%0A%20%20%20%20%2F%2F%20Do%20%26%20of%20n%20with%20a%20number%20with%20all%20set%20bits%20except%0A%20%20%20%20%2F%2F%20the%20k’th%20bit%0A%20%20%20%20return%20(n%20%26%20~(1%20%3C%3C%20(k%20-%201)))%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20int%20n%20%3D%2015%3B%0A%20%20%20%20int%20k%20%3D%204%3B%0A%20%20%20%20cout%20%3C%3C%20turnOffK(n%2C%20k)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C++ Programming” highlight=”” provider=”manual”/]

Output:

7