C++ 中從二進位制數中移除一位以獲得最大值


討論一個問題,其中我們給定一個二進位制數。我們必須從中刪除一位,以便剩餘的數字應該是所有其他選項中的最大值,例如

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.

尋找解決方案的方法

暴力方法

應用暴力方法將得到最大結果數,即透過逐一刪除每一位,比較不同的結果,並得到最大結果。

但有一種**高效的方法**可以使用,即如果我們刪除最不重要的位。

高效方法

高效方法對結果數字的影響最小。

  • 首先,從右邊遍歷位。

  • 搜尋 0 並在第一個計數器上刪除它。

  • 如果找不到 0,則刪除任意一位。

示例

高效方法的 C++ 程式碼

#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;
}

輸出

Maximum number: 111

上述程式碼的解釋

  • 使用一個標誌變數,以便只消除一個 0。

  • 字元陣列 res 初始化為儲存結果數字。

  • 迴圈將執行到 n-1,因為我們需要儲存比原始數字少一個的元素。

結論

在本教程中,我們討論了在從中刪除一位後找到最大數字的方法。我們討論了兩種解決此問題的方法。

我們還為此編寫了 C++ 程式碼,我們可以在其他任何語言(如 C、Java、Python 等)中編寫。我們希望您覺得本教程有所幫助。

更新於: 2021 年 11 月 26 日

420 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.