Single Number

Given 2*n + 1 numbers, every numbers occurs twice except one, find it.

Example:

Given [1,2,2,1,3,4,3], return 4

Solution:

Due to the property of xor, we have a^a = 0. Therefore, a^b^a = b

Code:

public class Solution {

    public int singleNumber(int[] A) {
        // Write your code here
        int num = 0;
        for (int x : A) {
            num = num ^ x;
        }
        return num;
    }
}

results matching ""

    No results matching ""