Java [Leetcode 136]Single Number

题目描述:

Given an array of integers, every element appears twice except for one. Find that single one.

解题思路:

参考别人的想法,用异或的方法实在是太绝了。A ^ A = 0 and A ^ B ^ A = B,因为只有一个是单着的,那么其他成对的两数相异或的结果是0,最后与单着的数异或还是为这个数。

代码如下:

public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++){
        	result ^= nums[i];
        }
        return result;
    }
}

  

posted @ 2016-02-26 23:49  scottwang  阅读(224)  评论(0编辑  收藏  举报