Microsoft is a red mesh Java interview questions

topic:

Given an array of type int: int[] array = new int[]{12, 2, 3, 3, 34, 56, 77, 432},

Let the value at each location of the array elements to remove the results of the first position, resulting, as the new value at that location,

Traversing the new array

Typical wrong answers:

    public static void main(String[] args) {
        int[] array = new int[]{12, 2, 3, 3, 34, 56, 77, 432};

        for (int i = 0; i < array.length; i++) {
            array[i] = array[i] / array[0];
            // 注意这里,遍历第一次后,首位置元素的值变成了1,不再是12
        }

        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

A correct answer:

    public static void main(String[] args) {
        int[] array = new int[]{12, 2, 3, 3, 34, 56, 77, 432};

        int temp = array[0];
        for (int i = 0; i < array.length; i++) {
            array[i] = array[i] / temp;
        }

        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

The correct answer two:

    public static void main(String[] args) {
        int[] array = new int[]{12, 2, 3, 3, 34, 56, 77, 432};

        for (int i = array.length - 1; i >= 0; i--) {
            array[i] = array[i] / array[0];
        }

        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

Guess you like

Origin www.cnblogs.com/sum-41/p/11267276.html