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 };
时间: 2024-11-05 18:33:42