Find the Majority Element | Set 3 ( Bit Magic ) |  ; Number of bits in the integer ; Variable to calculate majority element ; Loop to iterate through all the bits of number ; Loop to iterate through all elements in array to count the total set bit at position i from right ; If the total set bits exceeds n / 2 , this bit should be present in majority Element . ; Iterate through array get the count of candidate majority element ; Verify if the count exceeds n / 2 ; Driver Code
function findMajority ( arr , n ) { let len = 32 ; let number = 0 ; for ( let i = 0 ; i < len ; i ++ ) { let countt = 0 ; for ( let j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) countt ++ ; } if ( countt > parseInt ( n / 2 , 10 ) ) number += ( 1 << i ) ; } let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( arr [ i ] == number ) count ++ ; if ( count > parseInt ( n / 2 , 10 ) ) document . write ( number ) ; else document . write ( " " ) ; } let arr = [ 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 ] ; let n = arr . length ; findMajority ( arr , n ) ;