Given a number n, the task is to toggle only first and last bits of a number
Input : 10 Output : 3 Binary representation of 10 is 1010. After toggling first and last bits, we get 0011. Input : 15 Output : 6
Prerequisite : Find MSB of given number.
1) Generate a number which contains first and last bit as set. We need to change all middle bits to 0 and keep corner bits as 1.
2) Answer is XOR of generated number and original number.
Time Complexity is 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 bits of a number except first and last bits
- Toggle the last m bits
- Print numbers having first and last bits as the only set bits
- Toggle all the bits of a number except k-th bit.
- 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
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle case of a string using Bitwise Operators
- Binary array after M range toggle operations
- Check if all bits can be made same by flipping two consecutive bits
- Unset the last m bits
- Rearrange array elements such that Bitwise AND of first N - 1 elements is equal to last element
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.
Improved By : Mithun Kumar