Leetcode# 136. Single Number(出现一次的数&异或)

来源:互联网 发布:淘宝怎么不能找人代付 编辑:程序博客网 时间:2024/05/18 15:51

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

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题意是说给你一个数组,只有一个数是出现一次的,其余数都出现两次,让你输入出现一次的数。

异或大法:相同为0,相反为原数

例如:a=1,b=1,c=9  

d=a^b^c=9

我的代码:

class Solution {public:    int singleNumber(vector<int>& nums) {        int res=0;        for(int i=0;i<nums.size();i++)            res^=nums[i];        return res;    }};

阅读全文
1 0