使用java对数组的所有子数组进行按位或求和

问题描述 投票:0回答:1

给定一个大小为 N 的整数数组 A。

子数组的值定义为其中所有元素的按位或。

返回 A % 10^9 + 7 的所有子数组的值之和。

public class Solution {
    public int solve(ArrayList<Integer> A) {
        long M = 1000000007;

        int N = A.size();
        
        long totalSubarrays = (N*(N+1))/2;
        long totalORSum = 0; //sum of bitwise OR of all subarrays
        
        //step1: traverse through each bit of element of array
        for(int i = 0; i < 32; i++) {
            long subArrayUnsetBit = 0;
            long zeroCount = 0;
            for(int j = 0; j < N; j++) {
                //2.check if bit is unset(0).count the number of unset bits.
                //Calculate the number of sub arrays with unset ith bit position

                //for each element, check if bit at "position" is unset
                //if it's unset, add to the total
                //since we are looking for number of subarrays, if there are continuous unset bit position, the number of subarrays will depend on it as well. 
                if ((1 & (A.get(j) >> i)) != 1) {
                    zeroCount++;
                } else {
                    subArrayUnsetBit = subArrayUnsetBit + (zeroCount * (zeroCount + 1)) / 2;
                    zeroCount = 0;//reset
                }

            }
            //get the number of subarrays which have ith bit as unset
            subArrayUnsetBit = subArrayUnsetBit + (zeroCount*(zeroCount+1))/2;
            //number of sub arrays which have ith bit set
            long subArraySetBit = totalSubarrays - subArrayUnsetBit;
            //if ith bit is set, its value would be: 2^i == (1<<i)
            long powerValue = (1<<i);
            //contribution to total sum by all subarrays which has set bit at ith position
            long contribution = (subArraySetBit * powerValue);
            totalORSum = (totalORSum + contribution);

        }
        return (int)(totalORSum % M);
        
    }
}

上面的代码对于小尺寸数组来说工作得很好,例如:[1,2,3,4,5]答案= 71。 但对于大型测试用例失败了。

请帮忙解决我缺少的东西?

java arrays bit-manipulation
1个回答
0
投票

通过将数组长度(N)更改为长数据类型。我能够有效地处理困难的测试用例。

int N = A.size();

long N = A.size();
© www.soinside.com 2019 - 2024. All rights reserved.