136. Single Number【LeetCode】异或运算符,算法,java

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?

题目分析:数字每一位存在数组中,每个数字承兑出现,只有一个数字只出现一次,我们知道异或运算符相同为0不同为1.

//按位与运算&

System.out.println(0&0);//0
System.out.println(0&1);//0
System.out.println(1&1);//1
System.out.println("===========");
//按位或运算符|
System.out.println(0|0);//0
System.out.println(0|1);//1
System.out.println(1|1);//1
System.out.println("===========");
//异或运算符^
System.out.println(0^0);//0
System.out.println(0^1);//1
System.out.println(1^1);//0
System.out.println("===========");
public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        int n =nums.length;
        for (int i = 0; i<n; i++)
        {
            result ^=nums[i];
        }
            return result;
    }
}

 

posted @ 2017-08-12 16:20  这个手杀不太0  阅读(242)  评论(7编辑  收藏  举报