How do I reverse an int array in Java?

前端 未结 30 2450
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 07:18

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++)
{
    int temp =          


        
30条回答
  •  失恋的感觉
    2020-11-21 07:47

    If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.

    public static void reverseArray4(int[] array) {
        int len = array.length;
        for (int i = 0; i < len/2; i++) {
            array[i] = array[i] ^ array[len - i  - 1];
            array[len - i  - 1] = array[i] ^ array[len - i  - 1];
            array[i] = array[i] ^ array[len - i  - 1];
        }
    }
    

提交回复
热议问题