首页 > 其他 > 详细

Swap Without Extra Variable

时间:2017-08-14 11:21:26      阅读:266      评论:0      收藏:0      [点我收藏+]

Given two variables, x and y, swap two variables without using a third variable.

Example

Given x = 10, y = 5
Return 15.

思路:考察位运算,异或。 同一个数异或两次还是其本身。

 1 class Solution {
 2 public:
 3     /**
 4      * @param x an integer
 5      * @param y an integer
 6      * @return nothing
 7      */
 8     void swap(int &x, int &y) {
 9         // Write your code here
10         x = x ^ y;
11         y = x ^ y;
12         x = x ^ y;
13     }
14 };

 

 

Swap Without Extra Variable

原文:http://www.cnblogs.com/FLAGyuri/p/7356619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!