Remove One Bit from a Binary Number to Get Maximum Value in C++


Discuss a problem in which we are given a binary number. We have to remove a bit from it so that the remaining number should be the maximum of all the other options, for example

Input : N = 1011
Output: 111
Explanation: We need to remove one bit so removing 0 bit will give a maximum number than removing any 1’s bit. 111 > 101, 011.

Input: 111
Output: 11
Explanation: Since all the bits are 1 so we can remove any bit.

Approach to Find the Solution

Brute-Force Method

Applying brute force will give the maximum resultant number, i.e., by removing each bit one by one, comparing the different results, and getting the maximum result.

But there is one Efficient approach that it can use, i.e., if we remove the least redundant bit.

Efficient Approach

Efficient approach will affect least on the resultant number.

  • First, traverse through the bits from the right.

  • Search for 0 and remove it on the first counter.

  • If 0 is not found, then remove any bit.

Example

C++ Code for the Efficient Approach

#include <bits/stdc++.h>
using namespace std;
int main(){
    string str = "1011";
    bool flag = false;
    int n = str.length();
    // Initialising new array for
    char res[n - 1];
    int j = 0;
    // traversing through the binary number from right.
    for (int i = 0; j < n - 1; i++) {
        // if 0 is found then skip it.
        if (str[i] == '0' && flag == false) {
            flag = true;
            continue;
        }
        else
            res[j++] = str[i];
    }
    // printing the resulting string.
    cout << "Maximum number: " << res;
    return 0;
}

Output

Maximum number: 111

Explanation of the Above Code

  • A flag variable is used so that only one 0 is eliminated.

  • Character array res is initialized to store the resultant number.

  • Loop will run till n-1 because we need to store one less element than the original number.

Conclusion

In this tutorial, we discussed finding the maximum number after removing one bit from it. We discussed two approaches to solve this problem.

We also write C++ Code for the same, which we can write in any other language like C, Java, Python, etc. We hope you find this tutorial helpful.

Updated on: 26-Nov-2021

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements