首页  >  文章  >  后端开发  >  使用C++编写的至少包含一个非空子数组的按位与的数字

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

PHPz
PHPz转载
2023-09-09 09:33:04474浏览

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

上述代码说明

  • 声明set存储AND运算的所有结果。

  • 使用 INT_MAX 初始化“val”变量,因为我们需要将所有位设置为 1 进行 AND 运算。

  • 内部循环遍历第 i 个索引中的所有可能的子数组.

  • 将各个元素相互之间以及与自身之间进行AND运算并存储到结果集中。

  • 打印全部

结论

在本教程中,我们讨论了解决此问题的一种简单方法,即计算 AND 运算每个可能的子数组。我们还讨论了C++程序来解决这个问题。此外,您还可以使用任何其他语言(例如 Java、C、Python 等)编写此代码。我们希望本教程对您有所帮助。

以上是使用C++编写的至少包含一个非空子数组的按位与的数字的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除