Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a bit manipulation programs #46

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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;
}