|
18 | 18 | public class SingleNumber {
|
19 | 19 | public static void main (String args[]){
|
20 | 20 | // Create an array
|
21 |
| - int[] nums = {2,2,1}; |
| 21 | + int[] nums = {4,1,2,1,2}; |
22 | 22 |
|
23 | 23 | // Put the array in the singleNumber function and print the results
|
24 | 24 | System.out.println(singleNumber(nums));
|
25 | 25 | }
|
26 | 26 | 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; |
43 | 51 | }
|
44 | 52 | }
|
0 commit comments