Maximize a given unsigned number by swapping bits at its extreme positions in C++


Problem statement

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

If the input number is 8 then its binary representation is−

00000000 00000000 00000000 00001000

After swapping bits at extreme positions number becomes −

00010000 00000000 00000000 00000000 and its decimal equivalent is: 268435456

Algorithm

1. Create a copy of the original number
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. Return new number

Example

 Live Demo

#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;
ull getMaxNumber(ull num){
   ull origNum = num;
   int bitCnt = sizeof(ull) * 8 - 1;
   int cnt = 0;
   for(cnt = 0; cnt < bitCnt; ++cnt, --bitCnt) {
      int m = (origNum >> cnt) & 1;
      int n = (origNum >> bitCnt) & 1;
      if (m > n) {
         int x = (1 << cnt | 1 << bitCnt);
         num = num ^ x;
      }
   }
   return num;
}
int main(){
   ull num = 8;
   cout << "Maximum number = " << getMaxNumber(num) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Maximum number = 268435456

Updated on: 24-Dec-2019

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements