
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Maximize the number by rearranging bits in C++
- Program to maximize the number of equivalent pairs after swapping in Python
- Max Number By Swapping
- Minimum flips required to maximize a number with k set bits in C++.
- Add two unsigned numbers using bits in C++.
- Maximize the given number by replacing a segment of digits with the alternate digits given in C++
- Minimum number using set bits of a given number in C++
- Program to find longest number of 1s after swapping one pair of bits in Python
- Maximize number of 0s by flipping a subarray in C++
- Reverse actual bits of the given number in Java
- C program to rotate the bits for a given number
- Swapping adjacent binary bits of a decimal to yield another decimal using JavaScript
- Maximize the profit by selling at-most M products in C++
- Swapping string case using a binary number in JavaScript
- Program to find out the substrings of given strings at given positions in a set of all possible substrings in python

Advertisements