【发布时间】:2025-12-13 08:20:05
【问题描述】:
假设我有以下变量:
int x = 1;
int y = 2;
//some calculations follow(x and y stay the same init values) that somehow require you to interchange the values of y and x
如何在一行代码中设置 y = 1 和 x = 2??
【问题讨论】:
假设我有以下变量:
int x = 1;
int y = 2;
//some calculations follow(x and y stay the same init values) that somehow require you to interchange the values of y and x
如何在一行代码中设置 y = 1 和 x = 2??
【问题讨论】:
不知道为什么这是必要的,但你可以这样做:
int x = 2, y = 1;
【讨论】:
x = 2和y = 1。如果您想知道如何交换存储在x 和y 中的值,那是一个完全不同的问题。在这种情况下,你会想做int z = x, x = y, y = z;
尝试使用按位 XOR(^) 运算符。
x = x ^ y ^ (y = x);
您完成的代码可能看起来像,
class Main
{
public static void main (String[] args)
{
int x = 1, y = 2;
x = x ^ y ^ (y = x);
System.out.println("x after swapping:\nx="+x+"\ny after swapping,\ny="+y);
}
}
【讨论】: