[C#][LeetCode][136. Single Number]

X、O、R!

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?

給一個整數陣列,找出只出現過一次的單身狗

連續兩次XOR相同的值會得到原本的值,依照這特性用個for迴圈,從第一個值一直XOR到底就對了

Ex. 6對3做兩次XOR,會得到原本的6這個值

0110 XOR 0011 = 0101, 0101 XOR 0011 = 0110 = 6

 public int SingleNumber(int[] nums)
        {
            int result = nums[0]; //先取陣列第一個值
            for (int i = 1; i < nums.Length; i++) //從陣列第二個值開始
            {
                result ^= nums[i]; //進行XOR
            }
            return result;
        }

 

單純筆記,皆為非正規作法,旁門左道,胡搞瞎搞。