给定两个 int 变量, 交换变量的值.
1.创建变量i实现交换
2.不创建临时变量利用加减法实现
-
public class Solution { public static void main(String[] args) { int a=10; int b=20; b=b-a;//b=10 a=a+b;//a=20 System.out.printf("%d\n",a); System.out.printf("%d",b); } } -

3.利用异或实现
-
public class Solution { public static void main(String[] args) { int a=10;// 01010 int b=20;// 10100 b=a^b;// 11110 a=a^b;// 10100 b=a^b;// 01010 System.out.printf("%d\n",a); System.out.printf("%d",b); } }

本文介绍了三种在Java中交换两个整数变量值的方法:使用第三个变量、利用加减法和利用异或运算。每种方法都通过具体的代码示例进行了解释。

2628

被折叠的 条评论
为什么被折叠?



