136. Single Number
Question:
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?
Solution:
Logic: XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.
A ^ A = 0 and A ^ B ^ A = B.
class Solution { public: int singleNumber(int A[], int n) { int result=A[0]; for(int i=1;i<n;i++) { result= result^A[i]; /* Get the xor of all elements */ } return result; } };
题目直达:https://leetcode.com/problems/single-number/#/solutions