• 描述

编写一个函数,不用临时变量,直接交换numbers = [a, b]ab的值。

  • 示例:

输入: numbers = [1,2]
输出: [2,1]
提示:

numbers.length == 2

  • Solution One

简单的加法交换

class Solution {
    public int[] swapNumbers(int[] numbers) {
        numbers[0] += numbers[1];
        numbers[1] = numbers[0] - numbers[1];
        numbers[0] = numbers[0] - numbers[1];
        return numbers;
    }
}
  • Solution Two

异或运算

class Solution {
    public int[] swapNumbers(int[] numbers) {
        numbers[0] ^= numbers[1];
        numbers[1] ^= numbers[0];
        numbers[0] ^= numbers[1];
        return numbers;
    }
}