题目描述 - leetcode
Given an array of integers, every element appears twice except for one. Find that single one.
C 解答
int singleNumber(int* nums, int numsSize) {
int a = 0;
for (int i = 0; i < numsSize; i++) {
a = a ^ nums[i];
}
return a;
}
分析
XOR
The bitwise XOR (exclusive or) performs a logical XOR function, which is equivalent to adding two bits and discarding the carry. The result is zero only when we have two zeroes or two ones.
XOR can be used to toggle the bits between 1 and 0. Thus i = i ^ 1 when used in a loop toggles its values between 1 and 0.