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)
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.
- Toggle all the bits of a number except k-th bit.
- Toggle first and last bits of a number
- Toggle the last m bits
- Print numbers having first and last bits as the only set bits
- Toggle all even bits of a number
- Toggle all odd bits of a number
- For every set bit of a number toggle bits of other
- Toggle bits in the given range
- Toggle all bits after most significant bit
- Check whether the number has only first and last bits set
- Check whether the number has only first and last bits set | Set 2
- First and Last Three Bits
- Set, Clear and Toggle a given bit of a number in C
- Program to toggle K-th bit of a number N
- Toggle case of a string using Bitwise Operators
- Construct an array from XOR of all elements of array except element at same index
- Unique element in an array where all elements occur k times except one
- Rearrange array elements such that Bitwise AND of first N - 1 elements is equal to last element
- Unset the last m bits
- Check if bits of a number has count of consecutive set bits in increasing order
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.