Given a number, the task is to toggle bits of the number except the first and the last bit.
Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1
Prerequisite : Find most significant set bit of a number
1) Generate a number which contains middle bit as set. We need to change all middle bits to 1 and keep corner bits as 0.
2) Answer is XOR of generated number and original number. Note that XOR of 1 with a number toggles the number.
Time Complexity:- O(1)
- Toggle all odd bits of a number
- For every set bit of a number toggle bits of other
- Toggle all the bits of a number except k-th bit.
- Toggle first and last bits of a number
- Toggle all even 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
- Print numbers having first and last bits as the only set bits
- Set all odd bits of a number
- Same Number Of Set Bits As N
- Set all even bits of a number
- Check whether the number has only first and last bits set | Set 2
- Largest number less than X having at most K 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 email@example.com. 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.