Java [Leetcode 136]Single Number

时间:2016-02-27 00:45:55   收藏:0   阅读:190

题目描述:

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;
    }
}

  

原文:http://www.cnblogs.com/zihaowang/p/5222138.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!