程序员面试金典 - 面试题 16.01. 交换数字(位运算swap)

1. 题目

编写一个函数,不用临时变量,直接交换numbers = [a, b]中a与b的值。

示例:
输入: numbers = [1,2]
输出: [2,1]

提示:
numbers.length == 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-numbers-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 首先异或运算跟次序无关
  • a^a = 0, 0^a=a
  • a ^= b ^= a ^= b
  • 从右往左一个个的看
  • 第一个,a = a^b,b = b
  • 第二个,b = b^(a^b)=a,a=a^b
  • 第三个,a = (a^b)^a = b
  • 可以看到最后a,b的值互换了
class Solution {
public:
    vector<int> swapNumbers(vector<int>& n) {
        n[0] ^= n[1] ^= n[0] ^= n[1];
        return n;
    }
};

在这里插入图片描述

发布了691 篇原创文章 · 获赞 633 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/104668795