Número máximo de 1 consecutivos en representación binaria de todos los elementos de la array

Dada una array arr[] de N elementos, la tarea es encontrar el número máximo de 1 consecutivos en la representación binaria de un elemento entre todos los elementos de la array dada.

Ejemplos: 

Entrada: arr[] = {1, 2, 3, 4} 
Salida:
Binario(1) = 01 
Binario(2) = 10 
Binario(3) = 11 
Binario(4) = 100

Entrada: arr[] = {10, 15, 37, 89} 
Salida:

Enfoque: En este artículo se ha discutido un enfoque para encontrar el conteo del máximo de 1s consecutivos en la representación binaria de un número . Se puede usar el mismo enfoque para encontrar lo mismo para todos los elementos de la array dada y el máximo entre esos valores es la respuesta requerida.

A continuación se muestra la implementación del enfoque anterior: 

C++

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

Java

// Java implementation of the approach
class GFG
{
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation of x
static int maxConsecutiveOnes(int x)
{
    // Initialize result
    int count = 0;
 
    // Count the number of iterations to
    // reach x = 0.
    while (x != 0)
    {
        // This operation reduces length
        // of every sequence of 1s by one
        x = (x & (x << 1));
 
        count++;
    }
    return count;
}
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation among all
// the elements of arr[]
static int maxOnes(int arr[], int n)
{
    // To store the answer
    int ans = 0;
 
    // For every element of the array
    for (int i = 0; i < n; i++)
    {
 
        // Count of maximum consecutive 1s in
        // the binary representation of
        // the current element
        int currMax = maxConsecutiveOnes(arr[i]);
 
        // Update the maximum count so far
        ans = Math.max(ans, currMax);
    }
    return ans;
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = { 1, 2, 3, 4 };
    int n = arr.length;
 
    System.out.println(maxOnes(arr, n));
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
 
# Function to return the count of
# maximum consecutive 1s in the
# binary representation of x
def maxConsecutiveOnes(x) :
 
    # Initialize result
    count = 0;
 
    # Count the number of iterations to
    # reach x = 0.
    while (x != 0) :
         
        # This operation reduces length
        # of every sequence of 1s by one
        x = (x & (x << 1));
 
        count += 1;
     
    return count;
 
# Function to return the count of
# maximum consecutive 1s in the
# binary representation among all
# the elements of arr[]
def maxOnes(arr, n) :
 
    # To store the answer
    ans = 0;
 
    # For every element of the array
    for i in range(n) :
 
        # Count of maximum consecutive 1s in
        # the binary representation of
        # the current element
        currMax = maxConsecutiveOnes(arr[i]);
 
        # Update the maximum count so far
        ans = max(ans, currMax);
 
    return ans;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4 ];
    n = len(arr);
 
    print(maxOnes(arr, n));
 
# This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
                     
class GFG
{
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation of x
static int maxConsecutiveOnes(int x)
{
    // Initialize result
    int count = 0;
 
    // Count the number of iterations to
    // reach x = 0.
    while (x != 0)
    {
        // This operation reduces length
        // of every sequence of 1s by one
        x = (x & (x << 1));
 
        count++;
    }
    return count;
}
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation among all
// the elements of arr[]
static int maxOnes(int []arr, int n)
{
    // To store the answer
    int ans = 0;
 
    // For every element of the array
    for (int i = 0; i < n; i++)
    {
 
        // Count of maximum consecutive 1s in
        // the binary representation of
        // the current element
        int currMax = maxConsecutiveOnes(arr[i]);
 
        // Update the maximum count so far
        ans = Math.Max(ans, currMax);
    }
    return ans;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 1, 2, 3, 4 };
    int n = arr.Length;
 
    Console.WriteLine(maxOnes(arr, n));
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// javascript implementation of the approach
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation of x
function maxConsecutiveOnes(x)
{
    // Initialize result
    var count = 0;
 
    // Count the number of iterations to
    // reach x = 0.
    while (x != 0)
    {
        // This operation reduces length
        // of every sequence of 1s by one
        x = (x & (x << 1));
 
        count++;
    }
    return count;
}
 
// Function to return the count of
// maximum consecutive 1s in the
// binary representation among all
// the elements of arr
function maxOnes(arr , n)
{
    // To store the answer
    var ans = 0;
 
    // For every element of the array
    for (i = 0; i < n; i++)
    {
 
        // Count of maximum consecutive 1s in
        // the binary representation of
        // the current element
        var currMax = maxConsecutiveOnes(arr[i]);
 
        // Update the maximum count so far
        ans = Math.max(ans, currMax);
    }
    return ans;
}
 
// Driver code
var arr = [ 1, 2, 3, 4 ];
var n = arr.length;
 
document.write(maxOnes(arr, n));
 
// This code contributed by Princi Singh
 
</script>
Producción

2

Complejidad de tiempo: O(N*log(maxArr)), ya que estamos usando un ciclo para recorrer N veces y en cada recorrido, estamos llamando a la función maxConsecutiveOnes que costará log(maxArr). Donde N es el número de elementos en el arreglo y maxArr es el elemento con valor máximo en el arreglo.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.

Publicación traducida automáticamente

Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *