Recuento de pares cuyo AND bit a bit es una potencia de 2

Dada una array arr[] de N enteros positivos. La tarea es encontrar el número de pares cuyo valor AND bit a bit es una potencia de 2.
Ejemplos: 
 

Entrada: arr[] = {2, 1, 3, 4} 
Salida:
Explicación: 
Hay 2 pares (2, 3) y (1, 3) en esta array cuyos valores AND bit a bit son: 
1. (2 y 3 ) = 1 = (2 0
2. (1 y 3) = 1 = (2 0 ).
Entrada: arr[] = {6, 4, 2, 3} 
Salida:
Explicación: 
Hay 4 pares (6, 4), (6, 2), (6, 3), (2, 3) cuyo bit a bit y es potencia de 2 
 

Enfoque: para cada par posible en la array dada, la idea de verificar si Bitwise AND de cada par de elementos es potencia perfecta de 2 o no. Si la respuesta es «Sí» , cuente este par. De lo contrario, verifique el próximo par.
A continuación se muestra la implementación del enfoque anterior:
 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if x is power of 2
bool check(int x)
{
    // Returns true if x is a power of 2
    return x && (!(x & (x - 1)));
}
 
// Function to return the
// number of valid pairs
int count(int arr[], int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for (int i = 0; i < n - 1; i++) {
 
        for (int j = i + 1; j < n; j++) {
 
            // Bitwise and value of
            // the pair is passed
            if (check(arr[i]
                      & arr[j]))
                cnt++;
        }
    }
 
    // Return the final count
    return cnt;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 6, 4, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << count(arr, n);
    return 0;
}

Java

// Java program for the above approach
class GFG{
 
// Method to check if x is power of 2
static boolean check(int x)
{
 
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
 
// Function to return the
// number of valid pairs
static int count(int arr[], int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for(int i = 0; i < n - 1; i++)
    {
       for(int j = i + 1; j < n; j++)
       {
           
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
     
    // Return the final count
    return cnt;
}
 
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = new int[]{ 6, 4, 2, 3 };
 
    int n = arr.length;
     
    // Function call
    System.out.print(count(arr, n));
}
}
 
// This code is contributed by Pratima Pandey

Python3

# Python3 program for the above approach
 
# Function to check if x is power of 2
def check(x):
     
    # Returns true if x is a power of 2
    return x and (not(x & (x - 1)))
 
# Function to return the
# number of valid pairs
def count(arr, n):
     
    cnt = 0
 
    # Iterate for all possible pairs
    for i in range(n - 1):
        for j in range(i + 1, n):
 
            # Bitwise and value of
            # the pair is passed
            if check(arr[i] & arr[j]):
                cnt = cnt + 1
 
    # Return the final count
    return cnt
 
# Given array
arr = [ 6, 4, 2, 3 ]
n = len(arr)
 
# Function Call
print(count(arr, n))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program for the above approach
using System;
class GFG{
 
// Method to check if x is power of 2
static bool check(int x)
{
     
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
 
// Function to return the
// number of valid pairs
static int count(int []arr, int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for(int i = 0; i < n - 1; i++)
    {
       for(int j = i + 1; j < n; j++)
       {
            
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
     
    // Return the final count
    return cnt;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int []arr = new int[]{ 6, 4, 2, 3 };
 
    int n = arr.Length;
     
    // Function call
    Console.Write(count(arr, n));
}
}
 
// This code is contributed by Code_Mech

Javascript

<script>
 
// JavaScript program to implement
// the above approach
 
// Method to check if x is power of 2
function check(x)
{
   
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
   
// Function to return the
// number of valid pairs
function count(arr, n)
{
    let cnt = 0;
   
    // Iterate for all possible pairs
    for(let i = 0; i < n - 1; i++)
    {
       for(let j = i + 1; j < n; j++)
       {
             
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
       
    // Return the final count
    return cnt;
}
 
// Driver code
    // Given array arr[]
    let arr = [ 6, 4, 2, 3 ];
   
    let n = arr.length;
       
    // Function call
    document.write(count(arr, n));
 
// This code is contributed by susmitakundugoaldanga.
</script>
Producción: 

4

 

Complejidad de Tiempo: O(N 2
Espacio Auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por shauryarehangfg 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 *