LeetCode—single-number(只有一个数字是单个的,其他的数字都是重复的)—java

题目描述

Given an array of integers, every element appears twiceexcept 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;对所有数字进行异或的结果就是答案;
  • 对于任何数x,都有x^x=0,x^0=x

代码

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

猜你喜欢

转载自blog.csdn.net/lynn_baby/article/details/80565005