Maximum number of consecutive 1 's in binary representation of all the array elements | C ++ implementation of the approach ; Function to return the count of maximum consecutive 1 s in the binary representation of x ; Initialize result ; Count the number of iterations to reach x = 0. ; This operation reduces length of every sequence of 1 s by one ; Function to return the count of maximum consecutive 1 s in the binary representation among all the elements of arr [ ] ; To store the answer ; For every element of the array ; Count of maximum consecutive 1 s in the binary representation of the current element ; Update the maximum count so far ; Driver code
#include <iostream> NEW_LINE using namespace std ; int maxConsecutiveOnes ( int x ) { int count = 0 ; while ( x != 0 ) { x = ( x & ( x << 1 ) ) ; count ++ ; } return count ; } int maxOnes ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int currMax = maxConsecutiveOnes ( arr [ i ] ) ; ans = max ( ans , currMax ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxOnes ( arr , n ) ; return 0 ; }