使用C++编写的至少包含一个非空子数组的按位与的数字

使用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 }

寻找解决方案的方法

可以应用的简单方法是,

寻找所有可能的非空子数组。

遍历数组时,计算子数组中每个元素的按位与。

立即学习“C++免费学习笔记(深入)”;

为避免重复值,请将所有结果存储在一个集合中。

示例

#include 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 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++编写的至少包含一个非空子数组的按位与的数字的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444714.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 21:49:01
下一篇 2025年12月16日 09:48:18

相关推荐

发表回复

登录后才能评论
关注微信