From f6ff981b48d2faccea69293bed854cc21af1d544 Mon Sep 17 00:00:00 2001 From: ashwani361 Date: Mon, 4 Oct 2021 13:50:01 +0530 Subject: [PATCH] added a new solution --- .../Find_the_element_that_appears_once.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 999_Practice/Day_48/Find_the_element_that_appears_once.cpp diff --git a/999_Practice/Day_48/Find_the_element_that_appears_once.cpp b/999_Practice/Day_48/Find_the_element_that_appears_once.cpp new file mode 100644 index 0000000..df57637 --- /dev/null +++ b/999_Practice/Day_48/Find_the_element_that_appears_once.cpp @@ -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