
为了解决给定一个数组的问题,我们需要找到所有可能的整数,这些整数至少是一个非空子数组的按位与,例如 -
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 }可以应用的简单方法是,
寻找所有可能的非空子数组。
遍历数组时,计算子数组中每个元素的按位与。
立即学习“C++免费学习笔记(深入)”;
为避免重复值,请将所有结果存储在一个集合中。
#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中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号