
為了解決給定一個陣列的問題,我們需要找到所有可能的整數,這些整數至少是一個非空子數組的位元與,例如-
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
聲明set儲存AND運算的所有結果。
使用 INT_MAX 初始化「val」變量,因為我們需要將所有位元設為 1 進行 AND 運算。
內部迴圈遍歷第i 個索引中的所有可能的子數組.
將各個元素相互之間以及與自身之間進行AND運算並儲存到結果集中。
列印全部
#在本教程中,我們討論了解決此問題的簡單方法,即計算AND 運算每個可能的子數組。我們也討論了C 程式來解決這個問題。此外,您還可以使用任何其他語言(例如 Java、C、Python 等)編寫此程式碼。我們希望本教學對您有所幫助。
以上是使用C++編寫的至少包含一個非空子數組的位元與的數字的詳細內容。更多資訊請關注PHP中文網其他相關文章!