使用数组进行大数据运算

这里的大数据不是互联网上的大数据,而是指 比 long.maxValue还要大的数,因为基本类型已经满足不了大数据的计算。所以一般方法是采用数组。

 

下面是我自己的实现代码:

   /**
     * 两个数组进行计算
     * */
    public static int[] calculate(int[] value1,int[] value2){

        //存放每次循环乘的结果
        int tempLength = value1.length * 2 -1;
        int[][] temp = new int[value1.length][tempLength];
        //第一步,循环遍历第一个,依次乘以 value2的值,然后要留空位
        for (int i=value1.length -1;i>=0;i--){
            int[] tempValue = new int[tempLength];
            //预留几个 0
            int zeroLength = value1.length-1-i;
            //赋值
            for (int j= value2.length-1;j>=0;j--){
                int index = tempLength - zeroLength - (value2.length-j);
                tempValue[index] = value1[i] * value2[j];
            }
            temp[i] = tempValue;
        }

        //数组对应的每个值想加,行成一个新数组
        int[] sumArr = new int[tempLength];
        for (int i=0;i<temp.length;i++){
            for (int j=0;j<temp[i].length;j++){
                sumArr[j]+= temp[i][j];
            }
        }

        for (int i=sumArr.length-1;i>0;i--){
            sumArr[i-1] += sumArr[i] / 10;
            sumArr[i] = sumArr[i] % 10;//取余数
        }
        return sumArr;
    }

 

posted @ 2018-01-22 13:39  丶Pz  阅读(906)  评论(0编辑  收藏  举报