美文网首页
Swap the values of two integer

Swap the values of two integer

作者: 成江 | 来源:发表于2017-12-24 23:23 被阅读6次

Method one, use a temp variable

int a = 10;
int b = 11;
int temp = a;
a = b;
b = temp;

Method two, arithmetic

int a = 10;
int b = 11;
a = a + b; 
b = a - b;
a = a - b; // now b = a, which means a = a + b - a

The problem of this method is that it might overflow when a and b are very large. In other words, a + b is bigger than the range of int.

Method three, bit manipulation

int a = 10;
int b = 11;
a = a ^ b; 
b = a ^ b; // Now, b = 10 ^ 11 ^ 11 = 10, coz 11 ^ 11 = 0, 10 ^ 0 = 10
a = a ^ b;

There is no overflow problem here. Moreover, we don't need a temp variable. Of course, the first method, it is much more straight forward and much easier to maintain.

相关文章

网友评论

      本文标题: Swap the values of two integer

      本文链接:https://www.haomeiwen.com/subject/ukrkgxtx.html