用另一个数组中的值填充多维数组

时间:2019-02-05 10:52:15

标签: java arrays sorting multidimensional-array

我需要编写一个方法,该方法将返回由给定数组中的元素组成的多维数组,每行应具有具有相应数字位数的数字,例如,第一行应具有一位数字,第二行应具有数字两位数,第三行数字3位。

我设法对给定的数组进行排序。我进行了惨痛的尝试,以计算一个数字有多少位数。我无法理解下一步该怎么做。

感谢任何帮助。

class test {
    public static void main(String [] args){
        int arr[] = {20,11,100,9,3,200,4000};
        method(arr);
    }

    public static int[][] method(int arr[]){
        int arr1[][] = new int[50][50];
        for(int j=0;j<arr.length-1;j++){
            int minIndex = j;
            for(int i=j+1;i<arr.length;i++){
                if(arr[minIndex]>arr[i]){
                    minIndex = i;
                }
            }
            int temp = arr[minIndex];
            arr[minIndex] = arr[j];
            arr[j] = temp;
        }

        int k =0;
        while(k<arr.length) {
            int counter = 0;

            while (arr[k] != 0) {
                arr[k] /= 10;
                counter++;
            }
            k++;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

使用List可以更轻松地完成此操作,因为向数组添加元素并不容易。 阅读下面代码中的注释以查看其工作原理

public static void main(String args[]) throws Exception {

    int arr[] = {20,11,100,9,3,200,4000};

    int[][] sortedArray = new int[50][]; // fixing the size to 50 so we can go up to 50 digits, that could also be dynamic but it would make the code heavier
    int nbDigits;
    int[] tmpArray;
    for(int i : arr) {
        // get the number of digits
        nbDigits = nbDigits(i);

        // retrieve the array to add the integer to
        tmpArray = sortedArray[nbDigits-1];

        // add the integer to the array
        tmpArray = addToArray(tmpArray, i);

        // stick back your array in the multidimensional array
        sortedArray[nbDigits-1] = tmpArray;
    }
}

此方法将元素添加到给定数组。

private static int[] addToArray(int[] array, int n) {
    int[] returnArray;
    if(array == null) {
        returnArray = new int[1];
        returnArray[0] = n;
    } else {
        // copy the array in an other array 1 bigger
        returnArray = Arrays.copyOf(array, array.length + 1);
        // add your number at the end
        returnArray[array.length] = n;
    }
    return returnArray;
}

此方法通过将其设为字符串并返回其长度来计算整数的位数

private static int nbDigits(int n) {
    return String.valueOf(n).length();
}
相关问题