Open In App

Find element with the maximum set bits in an array

Last Updated : 26 Nov, 2021
Comments
Improve
Suggest changes
1 Like
Like
Report

Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.
Examples: 
 

Input: arr[] = {10, 100, 1000, 10000} 
Output: 1000 
Binary(10) = 1010 (2 set bits) 
Binary(100) = 1100100 (3 set bits) 
Binary(1000) = 1111101000 (6 set bits) 
Binary(10000) = 10011100010000 (5 set bits)
Input: arr[] = {3, 2, 4, 7, 1, 10, 5, 8, 9, 6} 
Output:
 


 


Approach: Traverse the array and find the count of set bits in the current element and find the element with the maximum number of set bits.
Below is the implementation of the above approach:
 

C++
Java Python3 C# PHP JavaScript

Output: 
7

 

Time Complexity: O(n)

Auxiliary Space: O(1)


Next Article

Similar Reads