Jayakrishna14

Sum of AND of subarrays

Jun 4th, 2025 (edited)
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5.     static long SumofAndOfSubarrays(int[] arr, int n){
  6.         long sum = 0;
  7.         for(int i=0; i<18; i++){ //since 1e5 don;t cross 18 bits
  8.             int contiguousOnes = 0;
  9.             int currContiguousOnes = 0;
  10.             for(int j=0; j<n; j++){
  11.                 if((arr[j]&(1<<i))  != 0) {
  12.                     currContiguousOnes++;
  13.                     contiguousOnes+=currContiguousOnes;
  14.                 } else {
  15.                     currContiguousOnes= 0;
  16.                 }
  17.             }
  18.             long SubarraysWithIthPlaceAsOne = contiguousOnes;
  19.             sum += SubarraysWithIthPlaceAsOne*(1 << i);
  20.         }
  21.  
  22.         return sum;
  23.     }
  24.  
  25.     public static void main(String[] args) {
  26.         Scanner sc = new Scanner(System.in);
  27.         int Q = sc.nextInt();
  28.         while(Q-- > 0){
  29.             int n = sc.nextInt();
  30.             int[] arr = new int[n];
  31.             for(int i=0; i<n; i++) arr[i] = sc.nextInt();
  32.  
  33.             System.out.println(SumofAndOfSubarrays(arr, n));
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment