VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-given-unsigned-number-number-swapping-bits-extreme-positions/

⇱ Maximize a given unsigned number by swapping bits at it's extreme positions. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize a given unsigned number by swapping bits at it's extreme positions.

Last Updated : 15 Nov, 2022

Given a number maximize it by swapping bits at its extreme positions i.e. at the first and last position, second and second last position, and so on. 

Examples: 

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.


Naive Approach: 
1. Convert the number into its bit representation and store its 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 the less significant bit is 1 and the more significant bit is 0 then swap them else take no action.
3. Convert the obtained binary representation back to the number.
Efficient Approach: 
1. Create a copy of the original number because the original number would be modified, iteratively obtaining the bits at the extreme positions.
2. If less significant bit is 1 and the more significant bit is 0 then swap the bits in the bit from only, and continue the process until less significant bit's position is less than more significant bit's position.
3. Display the maximized number. 
 


Output
536870912

Time Complexity: O(1)
Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: