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