Unique element in an array where all elements occur K times except one | Set 2 | 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
function findunique ( a , k ) { var res = 0 ; for ( var i = 0 ; i < 32 ; i ++ ) { var p = 0 ; for ( var j = 0 ; j < a . length ; j ++ ) { p += ( Math . abs ( a [ j ] ) & ( 1 << i ) ) != 0 ? 1 : 0 ; } p %= k ; res += Math . pow ( 2 , i ) * p ; } var c = 0 ; for ( var i = 0 ; i < a . length ; i ++ ) if ( a [ i ] == res ) { c = 1 ; break ; } return c == 1 ? res : - res ; } var a = [ 12 , 12 , 2 , 2 , 3 ] ; var k = 2 ; document . write ( findunique ( a , k ) + " " ) ;