How do I reverse an int array in Java?

前端 未结 30 2412
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    Using the XOR solution to avoid the temp variable your code should look like

    for(int i = 0; i < validData.length; i++){
        validData[i] = validData[i] ^ validData[validData.length - i - 1];
        validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
        validData[i] = validData[i] ^ validData[validData.length - i - 1];
    }
    

    See this link for a better explanation:

    http://betterexplained.com/articles/swap-two-variables-using-xor/

提交回复
热议问题