Skip to content

Latest commit

 

History

History
103 lines (79 loc) · 1.92 KB

README.md

File metadata and controls

103 lines (79 loc) · 1.92 KB

English Version

题目描述

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

示例:

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

提示:

  • numbers.length == 2

解法

异或运算。

Python3

class Solution:
    def swapNumbers(self, numbers: List[int]) -> List[int]:
        numbers[0] ^= numbers[1]
        numbers[1] ^= numbers[0]
        numbers[0] ^= numbers[1]
        return numbers

Java

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

TypeScript

function swapNumbers(numbers: number[]): number[] {
    numbers[0] ^= numbers[1];
    numbers[1] ^= numbers[0];
    numbers[0] ^= numbers[1];
    return numbers;
}
function swapNumbers(numbers: number[]): number[] {
    [numbers[0], numbers[1]] = [numbers[1], numbers[0]];
    return numbers;
}

C++

class Solution {
public:
    vector<int> swapNumbers(vector<int>& numbers) {
        numbers[0] ^= numbers[1];
        numbers[1] ^= numbers[0];
        numbers[0] ^= numbers[1];
        return numbers;
    }
};

Go

func swapNumbers(numbers []int) []int {
	numbers[0] ^= numbers[1]
	numbers[1] ^= numbers[0]
	numbers[0] ^= numbers[1]
	return numbers
}

...