Unique element in an array where all elements occur K times except one | Set 2 | CPP program for the above approach ; Function to find single occurrence element ; By shifting 1 to left ith time and taking and with 1 will give us that ith bit of a [ j ] is 1 or 0 ; Taking modulo of p with k ; Generate result ; Loop for negative numbers ; Check if the calculated value res is present in array , then mark c = 1 and if c = 1 return res else res must be - ve ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findunique ( vector < int > & a , int k ) { int res = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int p = 0 ; for ( int j = 0 ; j < a . size ( ) ; j ++ ) { p += ( abs ( a [ j ] ) & ( 1 << i ) ) != 0 ? 1 : 0 ; } p %= k ; res += pow ( 2 , i ) * p ; } int c = 0 ; for ( auto x : a ) if ( x == res ) { c = 1 ; break ; } return c == 1 ? res : - res ; } int main ( ) { vector < int > a = { 12 , 12 , 2 , 2 , 3 } ; int k = 2 ; cout << findunique ( a , k ) << " STRNEWLINE " ; }