#异或法
#Kotlin
```Kotlin
class Solution {
fun swapNumbers(numbers: IntArray): IntArray {
numbers[0] = numbers[0] xor numbers[1]
numbers[1] = numbers[1] xor numbers[0]
numbers[0] = numbers[0] xor 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; } }
#Scala
object Solution { def swapNumbers(numbers: Array[Int]): Array[Int] = { numbers(0)^= numbers(1) numbers(1)^= numbers(0) numbers(0)^= numbers(1) numbers } }
#C
int* swapNumbers(int* numbers, int numbersSize, int* returnSize)
{
*returnSize=2;
numbers[0]^=numbers[1];
numbers[1]^=numbers[0];
numbers[0]^=numbers[1];
return numbers;
}
#Rust
````Rust
impl Solution {
pub fn swap_numbers(mut numbers: Vec<i32>) -> Vec<i32> {
numbers[0] ^= numbers[1];
numbers[1] ^= numbers[0];
numbers[0] ^= numbers[1];
numbers
}
}
````
加减法
#Kotlin
```Kotlin
class Solution {
fun swapNumbers(numbers: IntArray): IntArray {
numbers[0] = numbers[0] -numbers[1]
numbers[1] = numbers[1] +numbers[0]
numbers[0] = numbers[0] -numbers[1]
return numbers
}
}
```
#Java
class Solution { public int[] swapNumbers(int[] numbers) { numbers[0] = numbers[0] -numbers[1] ; numbers[1] = numbers[1] +numbers[0] ; numbers[0] = numbers[0] -numbers[1] ; return numbers; } }
#Scala
object Solution { def swapNumbers(numbers: Array[Int]): Array[Int] = { numbers(1) = numbers(1) - numbers(0) numbers(0) = numbers(0) + numbers(1) numbers(1) = numbers(0) - numbers(1) numbers(0) = numbers(0) - numbers(1) numbers }
}
#C
由于使用int取值范围会越界产生溢出,所以使用无符号类型
```C
/**incle * Note: The returned array must be malloced, assume caller calls free(). */ int* swapNumbers (unsigned int* numbers, unsigned int numbersSize, int* returnSize) { numbers[1] = numbers[1] - numbers[0]; numbers[0] = numbers[0] + numbers[1]; numbers[1] = numbers[0] - numbers[1]; *returnSize = 2; return numbers; }
#Rust
```Rust
impl Solution {
pub fn swap_numbers(numbers: Vec<i32>) -> Vec<i32> {
let mut numbers = numbers;
numbers[0] = numbers[0] + numbers[1];
numbers[1] = numbers[0] - numbers[1];
numbers[0] = numbers[0] - numbers[1];
numbers
}
}
```
版权声明:本文原来写于CSDN博主「KloseYu 11也就是我的CSDN」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_46059871/article/details/134399399