You are given an array a consisting of n integers. A subarray (l, r) from array a is defined as non-empty sequence of consecutive elements al, al + 1, …, ar.
The beauty of a subarray (l, r) is calculated as the bitwise AND for all elements in the subarray:
Beauty(l, r) = al & al + 1 & al + 2 & … & ar
Your task is to calculate the summation of the beauty of all subarrays (l, r) (1 ≤ l ≤ r ≤ n):
Input
The first line contains an integer T, where T is the number of test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 105), where n is the size of the array a.
The second line of each test case contains n integers a1, a2, …, an (1 ≤ ai ≤ 106), giving the array a.
Output
For each test case, print a single line containing the summation of the beauty of all subarrays in the given array.
Example
Input
2
3
7 11 9
4
11 9 6 11
Output
40
48
位操作题,第一次做这种的只能喊666。
师兄指导说把二进制全部写出来找规律,6666。
题解看注释。
public class Main {
static final int MAX_BIT = 20;// ai最大是10的6次幂,转成二进制是20位。
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = reader.nextInt();
while (t-- > 0) {
int n = reader.nextInt();
int[] cnt = new int[MAX_BIT];
long res = 0;
for (int i = 0; i < n; i++) {
int get = reader.nextInt();
for (int j = 0; j < MAX_BIT; j++) {
if ((get >> j & 1) == 1) {// 判断每一位是不是1!
// 如果是,记录
cnt[j]++;
// 转回10进制累加
res += (long) cnt[j] << j;// 因为这里没转long一直wa...左移真是太容易爆了
continue;
}
cnt[j] = 0;// 一旦不是就归零(与操作的特点)
// 顺便把后面的位也都归零了....不然影响结果,这就是为什么硬要循环20次
}
}
out.println(res);
}
out.close();
}
}