[LeetCode136]Single Number寻找一个数组里只出现一次的数

题目:

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?

中文(给定一个整数的数组,每个整数都出现了两次,只有一个出现了一次,找到它  建议不使用额外的内存空间)

思路:利用^运算符  

二元 ^ 运算符是为整型和 bool 类型预定义的。对于整型,^ 将计算操作数的按位“异或”。对于 bool 操作数,^ 将计算操作数的逻辑“异或”;也就是说,当且仅当只有一个操作数为 true 时,结果才为 true。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeetCode
{
    class SingleNumberSolution
    {
        //static void Main()
        //{
        //    SingleNumberSolution s = new SingleNumberSolution();
        //    int[] nums = {1, 1, 2, 3, 3, 4, 4};
        //    Console.WriteLine(s.SingleNumber(nums));
        //}

        public int SingleNumber(int[] nums)
        {
            int singleNum = nums[0];
            for (int i = 1; i < nums.Length; i++)
            {
                singleNum ^= nums[i];
            }
            return singleNum;
        }
    }
}
原文地址:https://www.cnblogs.com/zhangbaochong/p/5058315.html