Java solution with explanation


  • 28
    H
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res = res^nums[i];
        }
        return res;
    }
    

    idea: for every bit, use bit manipulation. 0^0^0 = 0, 1^1^1 = 1, 0^0^1 = 1, 1^1^0 = 0. Thus, after the bit manipulation of XOR, the every bit of result is the bit of single number.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.