码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Without Extra Variable

时间:2017-08-14 11:25:04      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:and   bsp   运算   panel   without   integer   body   param   str   

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

标签:and   bsp   运算   panel   without   integer   body   param   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!