Given a number n and a value k, turn on the k’th bit in n.
Input: n = 4, k = 2 Output: 6 Input: n = 3, k = 3 Output: 7 Input: n = 64, k = 4 Output: 72 Input: n = 64, k = 5 Output: 80
The idea is to use bitwise << and | operators. Using expression "(1 << (k – 1))“, we get a number which has all bits unset, 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 1.
Below is the implementation of above idea.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to turn off a particular bit in a number?
- Turn off the rightmost set bit
- Turn off the rightmost set bit | Set 2
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Count number of trailing zeros in Binary representation of a number using Bitset
- Find the largest number smaller than integer N with maximum number of set bits
- Find a number which give minimum sum when XOR with every number of array of integers
- Number of ways to split a binary number such that every part is divisible by 2
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Minimum number of given powers of 2 required to represent a number
- Number of leading zeros in binary representation of a given number
- Check if a number has same number of set and unset bits
- Maximum number of splits of a binary number
- Program to Convert BCD number into Decimal number
- Find the Number Occurring Odd Number of Times
- Next higher number with same number of set bits
- Find third number such that sum of all three number becomes prime
- M-th smallest number having k number of set bits.
- Number of pairs with Bitwise OR as Odd number
- Number of integers with odd number of set bits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.