实现两个整数变量的互换
1.需要添加第三方变量(开发中常用):
class Hello2 { public static void main(String[] args) { int x = 10; int y = 5; int temp; temp = x ; x = y; y = temp; System.out.println("x = " + x + ",y = " + y); } }
结果:
2.不需要第三方变量(1)(有弊端,有可能超过int的取值范围):
class Hello2 { public static void main(String[] args) { int x = 10; int y = 5; x = x + y; y = x - y; x = x - y; System.out.println("x = " + x + ",y = " + y); } }
结果:
不需要第三方变量(2)(用^来做):
class Hello2 { public static void main(String[] args) { int x = 10; int y = 5; x = x ^ y; y = x ^ y; x = x ^ y; System.out.println("x = " + x + ",y = " + y); } }
结果:
相关文章