Unique element in an array where all elements occur K times except one | Set 2 | Java 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
import java . util . Arrays ; class Main { public static int findunique ( int a [ ] , int k ) { int res = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int p = 0 ; for ( int j = 0 ; j < a . length ; j ++ ) { p += ( Math . abs ( a [ j ] ) & ( 1 << i ) ) != 0 ? 1 : 0 ; } p %= k ; res += Math . pow ( 2 , i ) * p ; } int c = 0 ; for ( int x = 0 ; x < a . length ; x ++ ) if ( a [ x ] == res ) { c = 1 ; break ; } return c == 1 ? res : - res ; } public static void main ( String [ ] args ) { int a [ ] = { 12 , 12 , 2 , 2 , 3 } ; int k = 2 ; System . out . println ( findunique ( a , k ) ) ; } }