给定大小为N的数组A ,其中, 。任务是找到所有可能的子阵列,然后将这些结果和所有的和。
例子:
Input : 1 2 3
Output : 0
All possible subarrays are
{1}, {2}, {3}, {1, 2}, {2, 3} and {1, 2, 3}
ANDs of these subarrays are 1, 2, 3, 0, 2, 0.
AND of these ANDs is 0.
Input : 100 500 1000
Output : 96
方法:
朴素的解决办法是找到所有的子阵列的AND,然后打印其结果AND。这将导致O(N 2 )解。
最佳解决方案:使用 i:e元素出现多少次无关紧要,并且AND ing仅算为一个。因此,我们的问题简化为仅找到数组所有元素的AND 。
下面是上述方法的实现。
C++
// C++ program to find of all the sub-arrays
#include
using namespace std;
// function to return AND of sub-arrays
int AND(int a[], int n)
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans &= a[i];
return ans;
}
// Driver program
int main()
{
int a[] = { 1, 2, 3 };
// size of the array
int n = sizeof(a) / sizeof(a[0]);
// print and of all subarrays
cout << AND(a, n);
return 0;
}
Java
//Java program to find of all the sub-arrays
public class GFG {
//function to return AND of sub-arrays
static int AND(int a[], int n)
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans &= a[i];
return ans;
}
// Driver code
public static void main(String[] args) {
int a[] = { 1, 2, 3 };
// size of the array
int n = a.length;
// print and of all subarrays
System.out.println(AND(a, n));
}
}
Python 3
# Python 3 Program to find of all the sub-arrays
# function to return AND of sub-arrays
def AND(a, n) :
ans = a[0]
for i in range(n) :
ans &= a[i]
return ans
# Driver Code
if __name__ == "__main__" :
a = [ 1, 2, 3]
# size of the array
n = len(a)
# print and of all subarrays
print(AND(a, n))
# This code is contributed by ANKITRAI1
C#
//C# program to find of all the sub-arrays
using System;
public class GFG {
//function to return AND of sub-arrays
static int AND(int []a, int n)
{
int ans = a[0];
for (int i = 0; i < n; ++i)
ans &= a[i];
return ans;
}
// Driver code
public static void Main() {
int []a = { 1, 2, 3 };
// size of the array
int n = a.Length;
// print and of all subarrays
Console.WriteLine(AND(a, n));
}
}
PHP
输出:
0
时间复杂度: O(N)