# JavaScript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts

We will write a JavaScript program to find the sum of an array by using bitwise OR after splitting the given array into two halves after K circular shifts. Our program will perform the task by taking an array and an integer K as inputs. First, we will split the array into two halves after performing K circular shifts. Then, we will perform bitwise OR on both the halves to get a new array. Finally, we will find the sum of the new array obtained from the bitwise OR operation.

## Approach

• First, perform K circular shifts on the given array.

• Split the shifted array into two halves.

• Perform a bitwise OR operation on each element of both halves of the array.

• Sum up all the elements obtained from step 3 to get the result.

• Return the result as the sum of the array after performing the bitwise OR operation and splitting the array into two halves.

## Example

Here is an example of how you can find the sum of an array using Bitwise OR after splitting the array into two halves after K circular shifts −

function splitArrayAndGetSum(array, k) {
let splitArray = [];
let sum = 0;

// Split the array into two halves after K circular shifts
for (let i = 0; i < array.length; i++) {
splitArray[i % 2] = splitArray[i % 2] | array[(i + k) % array.length];
}

// Get the sum of the two halves using Bitwise OR
for (let i = 0; i < splitArray.length; i++) {
sum = sum | splitArray[i];
}
return sum;
}
let array = [1, 2, 3, 4, 5, 6, 7];
let k = 3;
console.log(splitArrayAndGetSum(array, k));


## Explanation

• The function takes an array and an integer k as inputs.

• The variable splitArray is used to store the two halves of the array after it has been split.

• The variable sum is used to store the sum of the two halves of the array.

• In the first for loop, the array is split into two halves after k circular shifts. The array is split into two halves using the modulo operator %. The value of each element in the two halves is obtained using the bitwise OR operator | with the value of the corresponding element in the original array after k circular shifts.

• In the second for loop, the sum of the two halves is obtained using the bitwise OR operator |. The final result is stored in the variable sum.

• Finally, the splitArrayAndGetSum function returns the value of sum.

Updated on: 15-Mar-2023

114 Views