 # LeetCode-136- A number that appears only once

Posted on Aug. 10, 2023, 6:03 p.m. by Tammy Hood
Category: java

#### 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.

Description:

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

See the LeetCode website for an example.

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)); }}``