【位运算】面试题 16.01. 交换数字

面试题 16.01. 交换数字

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

示例:

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

提示:

numbers.length == 2
-2147483647 <= numbers[i] <= 2147483647

题解1:
a 与 b 互换,
a=a+b
b=a-b
a=a-b

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

题解2:
使用异或

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

你可能感兴趣的:(每天一道算法题,leetcode,算法,动态规划)