Single Number

Single Number

问题:

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

思路:

异或

我的方法:

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

别人的方法:

public class Solution {
    public int singleNumber(int[] A) {
        if(A == null || A.length == 0) {
            return -1;
        }
        int rst = 0;
        for (int i = 0; i < A.length; i++) {
            rst ^= A[i];
        }
        return rst;
    }
}
View Code

学习之处:

命名用rst比较简练

next:

if(null==numbers || numbers.length==0) return -1;
int singleNumber = numbers[0];
for(int i=1; i< numbers.length; i++){
singleNumber ^= numbers[i];
}
return singleNumber;

 

posted on 2015-03-04 10:37  zhouzhou0615  阅读(99)  评论(0编辑  收藏  举报

导航