Horje
Sum of bitwise OR of all subarrays

Given an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array.

Examples: 

Input : 1 2 3 4 5
Output : 71

Input : 6 5 4 3 2
Output : 84

First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and, with sum1 we will perform bitwise OR operation for each jth element, and add sum1 with sum. 

  1. Traverse the from 0th position to n-1. 
  2. For each ith variable we will perform bit wise OR operation on all the sub arrays to find the total sum. 

Repeat step until the whole array is traverse. 

C++

<?php
// PHP program to find
// sum of bitwise ors
// of all subarrays.
function totalSum($a,$n)
{
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
    $sum1 = 0;
 
    // perform Bitwise OR operation
    // on all the subarray present
    // in array
    for ($j = $i; $j < $n; $j++)
    {
 
        // OR operation
        $sum1 = ($sum1 | $a[$j]);
 
        // now add the sum after
        // performing the
        // Bitwise OR operation
        $sum = $sum + $sum1;
    }
}
return $sum;
}
 
// Driver code
$a = array(1, 2, 3, 4, 5);
$n = sizeof($a);
echo totalSum($a, $n);
 
// This code is contributed by mits
?>

Javascript

<script>
 
// Java program to find sum
// of bitwise ors of all subarrays.
function totalSum(a, n)
{
    let i, sum = 0, sum1 = 0, j;
 
    for (i = 0; i < n; i++)
    {
        sum1 = 0;
 
        // perform Bitwise OR operation
        // on all the subarray present
        // in array
        for (j = i; j < n; j++)
        {
 
            // OR operation
            sum1 = (sum1 | a[j]);
 
            // now add the sum after
            // performing the Bitwise
            // OR operation
            sum = sum + sum1;
        }
    }
    return sum;
}
 
// Driver code
    let a = [ 1, 2, 3, 4, 5 ];
    let n = a.length;
    document.write(totalSum(a,n));
 
// This code is contributed shivanisinghss2110
</script>

Output

71

Time Complexity: O(N*N)
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


Arrays

Related
Majority element in a circular array of 0&#039;s and 1&#039;s Majority element in a circular array of 0&#039;s and 1&#039;s
Count elements in the given range which have maximum number of divisors Count elements in the given range which have maximum number of divisors
Elements that occurred only once in the array Elements that occurred only once in the array
Longest subarray having average greater than or equal to x | Set-2 Longest subarray having average greater than or equal to x | Set-2
Sorting a dynamic 2-dimensional array of Strings Sorting a dynamic 2-dimensional array of Strings

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
8