Numbers that appear only once

Given an array of non-empty integers, each element occurs twice except for one. Find the element that appears only once.


Your algorithm should have linear time complexity. Can you do this without using extra space?

See the LeetCode website for an example.

Source: LeetCode Link:… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution one: binary operation

The XOR operator that utilizes binary operations
^The XOR operation is the binary digits in the same position 0 if they are the same and 1 if they are different
0^0=0, 1^0=1, 0^1=1, 1^1=0. So by going through the array, doing XOR for each number, and since the XOR is zero for every number that’s repeated, you end up with an element that only appears once.

public class LeetCode_136 { public static int singleNumber(int[] nums) { int result = 0; for (int i = 0; i < nums.length; i++) { result ^= nums[i]; } return result; } public static void main(String[] args) { int[] nums = new int[]{2, 2, 1}; System.out.println(singleNumber(nums)); }}

【 Daily Message 】
Your burdens will become gifts. Your troubles will light your way.