Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Bit Manipulation/maximizing_bits.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// C++ program to find maximum number by
// swapping extreme bits.
#include <bits/stdc++.h>
using namespace std;

#define ull unsigned long long int

ull findMax(ull num)
{
ull num_copy = num;

/* Traverse bits from both extremes */
int j = sizeof(unsigned long long int) * 8 - 1;
int i = 0;
while (i < j) {

// Obtaining i-th and j-th bits
int m = (num_copy >> i) & 1;
int n = (num_copy >> j) & 1;

/* Swapping the bits if lesser significant
is greater than higher significant
bit and accordingly modifying the number */
if (m > n) {
int x = (1 << i | 1 << j);
num = num ^ x;
}

i++;
j--;
}
return num;
}

// Driver code to run program
int main()
{
ull num = 4;
cout << findMax(num);
return 0;
}