Skip to content

added a new solution #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions 999_Practice/Day_48/Find_the_element_that_appears_once.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Java code to find the element
// that occur only once

class GFG {
// Method to find the element that occur only once
static int getSingle(int arr[], int n)
{
int ones = 0, twos = 0;
int common_bit_mask;

for (int i = 0; i < n; i++) {
/*"one & arr[i]" gives the bits that are there in
both 'ones' and new element from arr[]. We
add these bits to 'twos' using bitwise OR*/
twos = twos | (ones & arr[i]);

/*"one & arr[i]" gives the bits that are
there in both 'ones' and new element from arr[].
We add these bits to 'twos' using bitwise OR*/
ones = ones ^ arr[i];

/* The common bits are those bits which appear third time
So these bits should not be there in both 'ones' and 'twos'.
common_bit_mask contains all these bits as 0, so that the bits can
be removed from 'ones' and 'twos'*/
common_bit_mask = ~(ones & twos);

/*Remove common bits (the bits that appear third time) from 'ones'*/
ones &= common_bit_mask;

/*Remove common bits (the bits that appear third time) from 'twos'*/
twos &= common_bit_mask;
}
return ones;
}

// Driver method
public static void main(String args[])
{
int arr[] = { 3, 3, 2, 3 };
int n = arr.length;
System.out.println("The element with single occurrence is " + getSingle(arr, n));
}
}
// Code contributed by Rishab Jain