Given a positive (or unsigned) integer n, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right.
Input : n = 4294967295, k = 0 Output : 1 The number 4294967295 in 32 bits has all bits set. When we toggle all bits except last bit, we get 1. Input : n = 1, k = 1 Output : 4294967292 4294967262 has all bits toggled except second bit from right.
- Toggle bit at k-th position. We do it by finding a number with only k-th bit set (using 1 << k), then doing bitwise XOR of this number n.
- Toggle all bits of number obtained above using ~ (Bitwise negation)
This article is contributed by Mandula Vikitha. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Toggle bits of a number except first and last bits
- For every set bit of a number toggle bits of other
- Toggle all even bits of a number
- Toggle first and last bits of a number
- Toggle all odd bits of a number
- Toggle the last m bits
- Toggle all bits after most significant bit
- Toggle bits in the given range
- Check if bits of a number has count of consecutive set bits in increasing order
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Check if a number has same number of set and unset bits
- Set all odd bits of a number
- Set all even bits of a number
- Same Number Of Set Bits As N
- Largest number less than X having at most K set bits