使用 C++ 查詢至少一個非空子陣列的按位與的結果


為了解決一個問題,我們給定一個數組,我們需要找到所有可能的整數,這些整數是至少一個非空子陣列的按位與的結果,例如 -

Input : nums[ ] = { 3, 5, 1, 2, 8 }
Output : { 2, 5, 0, 3, 8, 1 }
Explanation:
2 is the bitwise AND of subarray {2},
5 is the bitwise AND of subarray {5},
0 is the bitwise AND of subarray {1, 2}, {2, 8} and {1, 2, 8},
3 is the bitwise AND of subarray {3},
8 is the bitwise AND of subarray {8},
1 is the bitwise AND of subarray {1}, {3, 5} and {3, 5, 1}.

Input : nums[ ] = { 2, 6, 3, 8, 1 }
Output: { 1, 8, 3, 6, 2, 0 }

解決方法

可以應用的一種**簡單方法**是,

  • 找到所有可能的非空子陣列。

  • 在遍歷陣列時,計算子陣列中每個元素的按位與。

  • 為了避免重複值,將所有結果儲存在一個集合中。

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
    int arr[] ={ 2, 6, 3, 8, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // Declaring set to store result of each AND operation.
    unordered_set<int> result;
    int val;
    // nested loops to traverse through all the possible non empty subarrays.
    for (int i = 0; i < n; ++i){
        for (int j = i, val = INT_MAX; j < n; ++j){
            val = val & arr[j];
            // storing result of AND operation
            result.insert(val);
        }
    }
    cout << "All possible numbers are: ";
    // printing all the values of set.
    for (auto i = result.begin(); i != result.end();i++)
        cout << *i << " ";
    return 0;
}

輸出

All possible numbers are: 1 8 3 6 0 2

以上程式碼的解釋

  • 宣告一個集合來儲存所有 AND 操作的結果。

  • 將變數“val”初始化為 INT_MAX,因為我們需要對所有位設定為 1 的值進行 AND 操作。

  • 在迴圈中遍歷從第 i 個索引開始的所有可能的子陣列。

  • 計算每個元素彼此之間以及自身之間的 AND 操作,並將結果儲存在結果集中。

  • 列印結果集中所有值。

結論

在本教程中,我們討論了一種解決此問題的簡單方法,即計算每個可能的子陣列中的 AND 操作。我們還討論了使用 C++ 語言解決此問題的程式。此外,您還可以使用其他語言(如 Java、C、Python 等)編寫此程式碼。我們希望您發現本教程有所幫助。

更新於: 2021 年 11 月 25 日

112 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.