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?

描述

一组数,除了一个数外,其余数都出现 2 次,找出那个数

分析

使用异或的方式,A ^ A = 0A ^ A ^ B = B

代码

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public int singleNumber(int[] nums) {

int num = 0, len = nums.length;

for (int i = 0; i < len; i++) {
num ^= nums[i];
}

return num;
}
}