Skip to content

Commit 21e2904

Browse files
committed
fix: make single number algorithm more accurate and efficient
1 parent 4673906 commit 21e2904

File tree

1 file changed

+25
-17
lines changed

1 file changed

+25
-17
lines changed

Algorithms/30 Day LeetCoding Challenge/SingleNumber.java

+25-17
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,35 @@
1818
public class SingleNumber {
1919
public static void main (String args[]){
2020
// Create an array
21-
int[] nums = {2,2,1};
21+
int[] nums = {4,1,2,1,2};
2222

2323
// Put the array in the singleNumber function and print the results
2424
System.out.println(singleNumber(nums));
2525
}
2626
public static int singleNumber(int[] nums) {
27-
// Take the first number of the array
28-
int num = nums[0];
29-
30-
/**
31-
* Traverse through the array from the beginning and do an
32-
* XOR comparison between num and every other number in the
33-
* array.
34-
*
35-
* XOR or Exclusive Or is a logical operation that outputs
36-
* true only when inputs differ (one is true, the other is
37-
* false)
38-
* */
39-
for (int i = 1; i < nums.length; i++) num ^= nums[i];
40-
41-
// Return the number that does not have a double
42-
return num;
27+
// Count the number of integers in the array
28+
int size = nums.length;
29+
// Isolate the first number in the array
30+
int result = nums[0];
31+
32+
// Traverse through the entire array starting from the second number
33+
for (int i = 1; i < size; i++)
34+
/**
35+
* Use an XOR gate to find the number without a match.
36+
*
37+
* XOR or Exclusive Or is a logical operation that outputs
38+
* true only when inputs differ (one is true, the other is
39+
* false).
40+
*
41+
* In this case, the program will traverse through the array
42+
* adding each number to the result variable
43+
* until it gets to the middle. After the
44+
* midpoint, it will subtract each subsequent number from
45+
* result
46+
* */
47+
result = result ^ nums[i];
48+
49+
// Return the "true" integer that does not appear twice
50+
return result;
4351
}
4452
}

0 commit comments

Comments
 (0)