Given a number maximize it by swapping bits at it’s extreme positions i.e. at first and last position, second and second last position and so on.
Input : 4 (0000...0100) Output : 536870912 (0010...0000) In the above example swapped 3rd and 3rd last bit to maximize the given unsigned number. Input : 12 (00000...1100) Output : 805306368 (0011000...0000) In the above example 3rd and 3rd last bit and 4th and 4th last bit are swapped to maximize the given unsigned number.
1. Convert the number into it’s bit representation and store it’s bit representation in an array.
2. Traverse the array from both ends, if the less significant bit of the bit representation is greater than the more significant bit i.e. if less significant bit is 1 and more significant bit is 0 then swap them else take no action.
3. Convert the obtained binary representation back to the number.
1. Create a copy of the original number because the original number would be modified, iteratively obtain the bits at the extreme positions.
2. If less significant bit is 1 and more significant bit is 0 then swap the bits in the bit from only, continue the process until less significant bit’s position is less than more significant bit’s position.
3. Display the maximized number.
This article is contributed by Aditya Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.