Difficulty Level: Rookie
Given a number n and a value k, turn of the k’th bit in n.
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.
Below is the implementation of above idea.
Exercise: Write a function turnOnK() that turns the k’th bit on.
This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- How to turn on a particular bit in a number?
- Turn off the rightmost set bit
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2
- Number of leading zeros in binary representation of a given number
- Build Lowest Number by Removing n digits from a given number
- Check if a number has same number of set and unset bits
- Largest even number possible by using one swap operation in given number
- Binary representation of next greater number with same number of 1's and 0's
- Minimize the number of replacements to get a string with same number of 'a', 'b' and 'c' in it
- Find the Number Occurring Odd Number of Times
- Check Whether a number is Duck Number or not
- Minimum number using set bits of a given number
Improved By : nitin mittal