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
def findMajority ( arr , n ) : NEW_LINE INDENT Len = 32 NEW_LINE number = 0 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] & ( 1 << i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > ( n // 2 ) ) : NEW_LINE INDENT number += ( 1 << i ) NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == number ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > ( n // 2 ) ) : NEW_LINE INDENT print ( number ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Majority ▁ Element ▁ Not ▁ Present " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE