Moment For Technology

LeetCode-136- A number that appears only once

Posted on Aug. 10, 2023, 6:03 p.m. by Tammy Hood
Category: java Tag: java algorithm leetcode LeetCode Personal Problem Solving Summary binary

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.
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.