两个数字交换的方法

来源:互联网 发布:mac phpstorm debug 编辑:程序博客网 时间:2024/05/21 15:45

方法一:(利用一个新的变量)

var x = 1;var y = 2var temp = x;x = y;y = temp;console.log(x)console.log(y)

输出结果:

21



方法二:(巧用+-运算符)(数字过大可能会溢出)

var x = 1;var y = 2;x = x + y;y = x - y;x = x - y;console.log(x)console.log(y)

输出结果:

21



方法三:(利用异或运算)(原理:一个数异或另一个数两次还等与这个数)

var x = 1;var y = 2;x = x ^ y;y = x ^ y;x = x ^ y;console.log(x)console.log(y)

输出结果:

21



附加(异或运算)

例:计算 5 ^ 8 = ?

计算原理:
5转换为二进制为 0101
8转换为二进制为 1000

    5 ^ 8
= 0101 ^ 1000 = 1101
= 13

原创粉丝点击