如何以最有效的方式在java中交换赋值?

5tmbdcev  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(273)

假设我有以下变量:

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??

xienkqul

xienkqul1#

不知道为什么这是必要的,但你可以这样做:

int x = 2, y = 1;
6psbrbz9

6psbrbz92#

尝试使用按位异或(^)运算符。

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);
    }
}

相关问题