Dadas dos strings s1 y s2 . La tarea es tomar un carácter de la primera string y un carácter de la segunda string y verificar si los valores ASCII de ambos caracteres tienen el mismo número de bits establecidos. Imprime el número total de dichos pares.
Ejemplos:
Entrada: s1 = “xcd”, s2 = “swa”
Salida: 1 El
único par válido es (d, a) con valores ASCII como 100 y 97 respectivamente.
Ambos contienen 3 bits establecidos.
Entrada: s1 = «geeks», s2 = «forgeeks»
Salida: 17
Acercarse:
- Cree dos arrays arr1 y arr2 de tamaño 6 con todos los valores inicializados en 0 para almacenar la frecuencia del número de bits establecidos. Dado que el número máximo de bits establecidos en alfabetos en minúsculas es 6.
- Recorre la string s1 y encuentra el valor ASCII de cada carácter. Almacene la frecuencia del número de bits establecidos de cada valor ASCII en una array arr1. (Por ejemplo, si hay 3 caracteres con 4 bits establecidos, almacene 3 en arr[4])
- Realice una operación similar para la string s2 y almacene su valor en otra array arr2.
- Inicialice una variable de conteo con 0.
- Para el número total de pares, siga agregando (arr1[i] * arr2[i]) en la variable de conteo para todos los valores válidos de i.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the count of valid pairs int totalPairs(string s1, string s2) { int count = 0; int arr1[7], arr2[7]; // Initialise both arrays with 0 for (int i = 1; i <= 6; i++) { arr1[i] = 0; arr2[i] = 0; } // Store frequency of number of set bits for s1 for (int i = 0; i < s1.length(); i++) { int set_bits = __builtin_popcount((int)s1[i]); arr1[set_bits]++; } // Store frequency of number of set bits for s2 for (int i = 0; i < s2.length(); i++) { int set_bits = __builtin_popcount((int)s2[i]); arr2[set_bits]++; } // Calculate total pairs for (int i = 1; i <= 6; i++) count += (arr1[i] * arr2[i]); // Return the count of valid pairs return count; } // Driver code int main() { string s1 = "geeks"; string s2 = "forgeeks"; cout << totalPairs(s1, s2); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the count of valid pairs static int totalPairs(String s1, String s2) { int count = 0; int[] arr1 = new int[7]; int[] arr2 = new int[7]; // Default Initialise both arrays 0 // Store frequency of number of set bits for s1 for (int i = 0; i < s1.length(); i++) { int set_bits = Integer.bitCount(s1.charAt(i)); arr1[set_bits]++; } // Store frequency of number of set bits for s2 for (int i = 0; i < s2.length(); i++) { int set_bits = Integer.bitCount(s2.charAt(i)); arr2[set_bits]++; } // Calculate total pairs for (int i = 1; i <= 6; i++) { count += (arr1[i] * arr2[i]); } // Return the count of valid pairs return count; } // Driver code public static void main(String[] args) { String s1 = "geeks"; String s2 = "forgeeks"; System.out.println(totalPairs(s1, s2)); } } // This code has been contributed by 29AjayKumar
Python3
# Python3 implementation of the approach # Function to get no of set bits in binary # representation of positive integer n def countSetBits(n): count = 0 while (n): count += n & 1 n >>= 1 return count # Function to return the count # of valid pairs def totalPairs(s1, s2) : count = 0; arr1 = [0] * 7; arr2 = [0] * 7; # Store frequency of number # of set bits for s1 for i in range(len(s1)) : set_bits = countSetBits(ord(s1[i])) arr1[set_bits] += 1; # Store frequency of number of # set bits for s2 for i in range(len(s2)) : set_bits = countSetBits(ord(s2[i])); arr2[set_bits] += 1; # Calculate total pairs for i in range(1, 7) : count += (arr1[i] * arr2[i]); # Return the count of valid pairs return count; # Driver code if __name__ == "__main__" : s1 = "geeks"; s2 = "forgeeks"; print(totalPairs(s1, s2)); # This code is contributed by Ryuga
C#
// C# implementation of the approach using System; using System.Linq; class GFG { // Function to return the count of valid pairs static int totalPairs(string s1, string s2) { int count = 0; int[] arr1 = new int[7]; int[] arr2 = new int[7]; // Default Initialise both arrays 0 // Store frequency of number of set bits for s1 for (int i = 0; i < s1.Length; i++) { int set_bits = Convert.ToString((int)s1[i], 2).Count(c => c == '1'); arr1[set_bits]++; } // Store frequency of number of set bits for s2 for (int i = 0; i < s2.Length; i++) { int set_bits = Convert.ToString((int)s2[i], 2).Count(c => c == '1'); arr2[set_bits]++; } // Calculate total pairs for (int i = 1; i <= 6; i++) count += (arr1[i] * arr2[i]); // Return the count of valid pairs return count; } // Driver code static void Main() { string s1 = "geeks"; string s2 = "forgeeks"; Console.WriteLine(totalPairs(s1, s2)); } } // This code is contributed by chandan_jnu
Javascript
<script> // JavaScript implementation of the approach // Function to get no of set bits in binary // representation of positive integer n function countSetBits(n) { var count = 0; while (n) { count += n & 1; n >>= 1; } return count; } // Function to return the count // of valid pairs function totalPairs(s1, s2) { var count = 0; var arr1 = new Array(7).fill(0); var arr2 = new Array(7).fill(0); // Store frequency of number // of set bits for s1 for (let i = 0; i < s1.length; i++) { set_bits = countSetBits(s1[i].charCodeAt(0)); arr1[set_bits] += 1; } // Store frequency of number of // set bits for s2 for (let i = 0; i < s2.length; i++) { set_bits = countSetBits(s2[i].charCodeAt(0)); arr2[set_bits] += 1; } // Calculate total pairs for (let i = 1; i < 7; i++) { count += arr1[i] * arr2[i]; } // Return the count of valid pairs return count; } // Driver code var s1 = "geeks"; var s2 = "forgeeks"; document.write(totalPairs(s1, s2)); </script>
Producción:
17
Publicación traducida automáticamente
Artículo escrito por Shashank_Sharma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA