Two odd occurring elements in an array where all other occur even times | PHP code to find two odd occurring elements in an array where all other elements appear even number of times . ; Find XOR of all numbers ; Find a set bit in the XOR ( We find rightmost set bit here ) ; Traverse through all numbers and divide them in two groups ( i ) Having set bit set at same position as the only set bit in set_bit ( ii ) Having 0 bit at same position as the only set bit in set_bit ; XOR of two different sets are our required numbers . ; Driver code
< ? php function printOdds ( $ arr , $ n ) { $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ res = $ res ^ $ arr [ $ i ] ; $ set_bit = $ res & ( ~ ( $ res - 1 ) ) ; $ x = 0 ; $ y = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] & $ set_bit ) $ x = $ x ^ $ arr [ $ i ] ; else $ y = $ y ^ $ arr [ $ i ] ; } echo ( $ x . " ▁ " . $ y ) ; } $ arr = array ( 2 , 3 , 3 , 4 , 4 , 5 ) ; $ n = sizeof ( $ arr ) ; printOdds ( $ arr , $ n ) ; ? >