Home  >  Article  >  Backend Development  >  In C++, remove one bit of a binary number to obtain the maximum value

In C++, remove one bit of a binary number to obtain the maximum value

PHPz
PHPzforward
2023-09-17 15:53:081091browse

In C++, remove one bit of a binary number to obtain the maximum value

Discuss the problem of a given binary number. We have to remove a little bit from it so that the remaining number should be the maximum among all other options like

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.

Solution method

Brute force method

Brute force method will give Get the maximum number of results, that is, remove them bit by bit, compare different results, and get the maximum result.

But it can be done using an efficient approach, that is, if we remove the minimum redundant bits.

Efficient methods

Efficient methods have the least impact on the results.

  • First, go through the bits starting from the right.

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

  • If 0 is not found, any bits are removed.

Example

C code for efficient method

#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] == &#39;0&#39; && flag == false) {
            flag = true;
            continue;
        }
        else
            res[j++] = str[i];
    }
    // printing the resulting string.
    cout << "Maximum number: " << res;
    return 0;
}

Output

Maximum number: 111

Description of the above code

  • Use a flag variable so that only one 0 is eliminated.

  • Initialize the character array res to store the result number.

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

  • The loop will run to n-1. p>

Conclusion

In this tutorial, we discussed finding the maximum number after removing one digit. We discussed two ways to solve this problem.

We have also written C code for this, we can write these codes in any other language like C, Java, Python etc. We hope you found this tutorial helpful.

The above is the detailed content of In C++, remove one bit of a binary number to obtain the maximum value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete