I am trying to find all the elements which occur an odd number of times in an array. I worked out a little bit, but my code is only returning the correct answer if there is only one number which occurs odd number of times. If there are two or more odd occurring numbers than I am not able to process it. What I understand is that if we do bit-wise XOR of elements than we get one odd occurring element. How can I improve it for multiple numbers?
Below is my code:
public class OddOccur {
public int oddoccurence(int[] arr, int size) {
int res = 0;
int[] fin = new int[size];
for (int i = 0; i < size; i++) {
res = res ^ arr[i];
}
return res;
}
public static void main(String args[]) {
int[] arr = { 2, 5, 5, 2, 2, 3, 3, 3 };
int n = arr.length;
OddOccur obj = new OddOccur();
System.out.println("odd occuring element is:"
+ obj.oddoccurence(arr, n));
}
}
Need help to solve this issue!