来源:http://www.javaeye.com/topic/645596
不使用第三个变量完成两个整数的交换,这个面试题大概大家都碰到过。如:
Java代码
public class Person {
public static void main(String[] args) {
//利用加减法
int a = 10, b = 5;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + "\nb=" + b);
}
}
还有另外一种方法,且效率更快:
Java代码
public class Person {
public static void main(String[] args) {
//利用一个数异或本身等于0和异或运算符合交换率
int a = 10, b = 5;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a=" + a + "\nb=" + b);
}
}
当然以上两种的算法对应js中也支持,如下:
JS代码
var a = 11,b = 22;
a = a + b;
b = a - b;
a = a - b;
console.log(a+'\n'+b)
或
JS代码
var a = 11,b = 22;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a+'\n'+b)
但如果两个变量是对象类型,java(强类型)貌似无能为力了。js却可以,实现方式还不少,如:
JS代码
var a = {name:'jack'},b = {name:'tom'};
a = [a,b];
b = a[0];
a = a[1];
console.log(a.name+'\n'+b.name)
或
JS代码
var a = {name:'jack'},b = {name:'tom'};
a = {a:a,b:b};
b = a.a;
a = a.b;
console.log(a.name+'\n'+b.name)
正是利用js动态类型(弱类型)系统及对象/数组直接量特性。其它强类型则不可以,编译器会提示类型转换错误。