Given an array A of size N where,
. The task is to find the OR of all possible sub-arrays of A and then the OR of all these results.
Examples:
Input : 1 4 6
Output : 7
All possible subarrays are
{1}, {1, 4}, {4, 6} and {1, 4, 6}
ORs of these subarrays are 1, 5, 6
and 7. OR of these ORs is 7.
Input : 10 100 1000
Output : 1006
Approach: In SET 1 we have seen how to find bitwise AND of all possible subarrays. A similar approach is also applicable here.
The Naive solution is to find the OR of all the sub-arrays and then output the OR of their results. This will lead to O(N2) solution.
Efficient Solution: Using the property that
i:e it doesn’t matter how many times an element comes, it’s ORing will be counted as one only. Thus our problem boils down to finding the OR of all the elements of the array.
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int OR( int a[], int n)
{
int ans = a[0];
for ( int i = 1; i < n; ++i)
ans |= a[i];
return ans;
}
int main()
{
int a[] = { 1, 4, 6 };
int n = sizeof (a) / sizeof (a[0]);
cout << OR(a, n);
return 0;
}
|
Java
class GFG
{
static int OR( int a[], int n)
{
int ans = a[ 0 ];
int i;
for (i = 1 ; i < n; i++)
{
ans |= a[i];
}
return ans;
}
public static void main(String args[])
{
int a[] = { 1 , 4 , 6 };
int n = a.length;
System.out.println(OR(a, n));
}
}
|
Python3
def OR(a, n):
ans = a[ 0 ]
for i in range ( 1 ,n):
ans | = a[i]
return ans
if __name__ = = '__main__' :
a = [ 1 , 4 , 6 ]
n = len (a)
print (OR(a, n))
|
C#
using System;
class GFG
{
static int OR( int [] a, int n)
{
int ans = a[0];
int i;
for (i = 1; i < n; i++)
{
ans |= a[i];
}
return ans;
}
public static void Main()
{
int [] a = { 1, 4, 6};
int n = a.Length;
Console.Write(OR(a, n));
}
}
|
PHP
<?php
function O_R( $a , $n )
{
$ans = $a [0];
for ( $i = 1; $i < $n ; ++ $i )
$ans |= $a [ $i ];
return $ans ;
}
$a = array ( 1, 4, 6 );
$n = count ( $a );
echo O_R( $a , $n );
?>
|
Javascript
<script>
function OR(a, n)
{
var ans = a[0];
for ( var i = 1; i < n; ++i)
ans |= a[i];
return ans;
}
var a = [ 1, 4, 6 ];
var n = a.length;
document.write(OR(a, n));
</script>
|
Output:
7
Time Complexity: O(N)