occur once – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 06 Aug 2019 15:28:51 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg occur once – Programmerbay https://programmerbay.com 32 32 Program to find the element which occur only once in an array https://programmerbay.com/program-to-find-the-element-which-occur-only-once-in-an-array/ https://programmerbay.com/program-to-find-the-element-which-occur-only-once-in-an-array/#respond Tue, 06 Aug 2019 15:28:51 +0000 https://www.programmerbay.com/?p=4479

Given an array with every element repeated twice except one. Find that element

In the solution we perform the XOR operation on all the elements in the array and store the result in a variable.

The XOR of any number with itself gives 0 as output.

The XOR of any number with 0 gives the number itself as output.

 

Program:

public class FindSingleElement {

	public static void main(String[] args) {

		int arr[]= {1,1,2,2,3,3,4,5,5,6,6};
		int res=0;

		for(int i=0; i<arr.length; i++)
			res= (res | arr[i]) & (~res | ~arr[i]);

		System.out.println("Element occurring only once is: "+res);
	}
}

Output:

Element occurring only once is: 4

 

]]>
https://programmerbay.com/program-to-find-the-element-which-occur-only-once-in-an-array/feed/ 0