^运算符的妙用

一.^运算符的基本使用方法

1.使用规则

^运算符首先将数字转化为二进制,随后采用异或的形式,即不同才返回1,相同返回0的方式

举例:

4^6
转化为
100^110=010

4^6=2

2.使用技巧

(1)
0异或任何数都得到原来的数

(2)
任何数异或自己都得0

(3)
相应的位数的任何数异或1将自己置反

二.算法中的两个巧用

1.不用中间临时量交换两个数字

a=a^b;
b=a^b;
a=a^b;

2.136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

贴上代码即可:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if(nums.size() == 0)
            return 0;
        int result = nums[0];
        for(int i = 1 ;i<nums.size();i++)
        {
            result = result ^ nums[i];
        }
        return result;
    }
};
posted @ 2017-07-26 20:26  vhyz  阅读(929)  评论(0编辑  收藏  举报