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
class GFG { static void findMajority ( int arr [ ] , int n ) { int len = 32 ; int number = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) count ++ ; } if ( count > ( n / 2 ) ) number += ( 1 << i ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == number ) count ++ ; if ( count > ( n / 2 ) ) System . out . println ( number ) ; else System . out . println ( " Majority ▁ Element ▁ Not ▁ Present " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 } ; int n = arr . length ; findMajority ( arr , n ) ; } }