Comprobar si la representación binaria de un número dado y su complemento son anagramas

Dado un número positivo, debe verificar si es un complemento y el número son anagramas o no.
Ejemplos: 
 

Input : a = 4294967295
Output : Yes
Binary representation of 'a' and it's
complement are anagrams of each other

Input : a = 4
Output : No

Enfoque simple: en este enfoque se permite el cálculo del complemento del número.
1. Encuentre la representación binaria del número y su complemento utilizando la técnica de representación decimal simple a binaria.
2. Ordene ambas representaciones binarias y compárelas para verificar si son anagramas o no.
 

CPP

// A simple C++ program to check if binary
// representations of a number and it's
// complement are anagram.
#include <bits/stdc++.h>
#define ull unsigned long long int
using namespace std;
 
const int ULL_SIZE = 8*sizeof(ull);
 
bool isComplementAnagram(ull a)
{
    ull b = ~a; // Finding complement of a;
 
    // Find reverse binary representation of a.
    bool binary_a[ULL_SIZE] = { 0 };
    for (int i=0; a > 0; i++)
    {
        binary_a[i] = a % 2;
        a /= 2;
    }
 
    // Find reverse binary representation
    // of complement.
    bool binary_b[ULL_SIZE] = { 0 };
    for (int i=0; b > 0; i++)
    {
        binary_b[i] = b % 2;
        b /= 2;
    }
 
    // Sort binary representations and compare
    // after sorting.
    sort(binary_a, binary_a + ULL_SIZE);
    sort(binary_b, binary_b + ULL_SIZE);
    for (int i = 0; i < ULL_SIZE; i++)
        if (binary_a[i] != binary_b[i])
            return false;
 
    return true;
}
 
// Driver code
int main()
{
    ull a = 4294967295;
    cout << isComplementAnagram(a) << endl;
    return 0;
}

Java

// A simple JAVA program to check if binary
// representations of a number and it's
// complement are anagram.
import java.math.BigInteger;
import java.util.*;
 
 
class GFG {
 
  // Method to discard the signed bit of the byte array
  // inorder to convert the numbers to unsigned
  static byte[] toUnsigned(byte[] byteArray)
  {
    BigInteger b = new BigInteger(byteArray);
    b = b.ONE.shiftLeft(128);
 
    return b.toByteArray();
  }
 
  //Method to check if a number and its complement
  //are anagrams
  static int isComplementAnagram(BigInteger a)
  {
    //converting a to an unsigned byte array
    byte[] binary_a = a.toByteArray();
    binary_a = toUnsigned(binary_a);
 
    //constructing byte array of complement of a
    byte[] binary_b = new byte[binary_a.length];
 
    //inverting the bits of a
    for (int i = 0; i < binary_a.length; i++)
    {
      binary_b[i] = (byte)(binary_a[i] ^ 0xFF);
    }
    binary_b = toUnsigned(binary_b);
 
    // Sort binary representations
    Arrays.sort(binary_a);
    Arrays.sort(binary_b);
 
    //converting a and ~a to unsigned after sorting
    binary_a = toUnsigned(binary_b);
    binary_b = toUnsigned(binary_b);
 
    //comparing the binary representations
    for (int i = 0; i < binary_a.length; i++)
      if (binary_a[i] != binary_b[i])
        return 0;
    return 1;
 
  }
 
  // Driver code
  public static void main(String[] args)
  {
    BigInteger a = new BigInteger("4294967295");
     
    // Function call
    System.out.println(isComplementAnagram(a));
  }
}
 
// This code is contributed by phasing17

Python3

# Python3  program to check if binary
# representations of a number and it's
# complement are anagram.
 
ULL_SIZE = 8 * 8
 
def isComplementAnagram(a):
 
    # Find reverse binary representation of a.
    binary_a = [0 for _ in range(ULL_SIZE)]
    binary_b = [0 for _ in range(ULL_SIZE)]
 
    i = 0
    while a > 0:
 
        binary_a[i] = a % 2
        a = int(a / 2)
        i += 1
 
    # Find reverse binary representation
    # of complement.
    for i in range(ULL_SIZE):
        binary_b[i] = 1 - binary_a[i]
 
    # Sort binary representations and compare
    # after sorting.
    binary_a.sort()
    binary_b.sort()
 
    for i in range(ULL_SIZE):
        if (binary_a[i] != binary_b[i]):
            return 0
 
    return 1
 
# Driver code
a = 4294967295
print(isComplementAnagram(a))
 
# This code is contributed by phasing17

Javascript

// JS  program to check if binary
// representations of a number and it's
// complement are anagram.
 
const ULL_SIZE = 8 * 8;
 
function isComplementAnagram(a)
{
 
    // Find reverse binary representation of a.
 
    var binary_a = new Array(ULL_SIZE).fill(0);
    var binary_b = new Array(ULL_SIZE).fill(0);
    for (var i = 0; a > 0; i++)
    {
        binary_a[i] = a % 2;
        a = Math.floor(a / 2);
    }
 
 
    // Find reverse binary representation
    // of complement.
    for (var i = 0; i < ULL_SIZE; i++)
    {
        binary_b[i] = 1 - binary_a[i];
    }
     
     
    // Sort binary representations and compare
    // after sorting.
    binary_a.sort();
    binary_b.sort();
 
 
    for (var i = 0; i < ULL_SIZE; i++)
        if (binary_a[i] != binary_b[i])
            return false;
 
    return true;
}
 
// Driver code
var a = 4294967295;
console.log(isComplementAnagram(a));
 
 
//This code is contributed by phasing17

Producción: 

1

Complejidad de tiempo: O(logn*log(logn)) donde n es el número dado.

Espacio Auxiliar: O(ULL_SIZE) donde ULL_SIZE se define constante.
Enfoque eficiente: simplemente cuente el número de 1 presentes en la representación de bits del número dado. Si el número de 1 presentes es 32, entonces su complemento también tendrá 32 1 en su representación de bits y serán anagramas entre sí. 
 

C++

// An efficient C++ program to check if binary
// representations of a number and it's complement are anagram.
#include <bits/stdc++.h>
#define ull unsigned long long int
using namespace std;
 
const int ULL_SIZE = 8*sizeof(ull);
 
// Returns true if binary representations of
// a and b are anagram.
bool bit_anagram_check(ull a)
{
    // _popcnt64(a) gives number of 1's present
    // in binary representation of a. If number
    // of 1s is half of total bits, return true.
    return (_popcnt64(a) == (ULL_SIZE >> 1));
}
 
int main()
{
    ull a = 4294967295;
    cout << bit_anagram_check(a) << endl;
    return 0;
}

Java

// An efficient Java program to check if binary
// representations of a number and it's complement are anagram.
class GFG
{
 
static byte longSize = 8;
static int ULL_SIZE = 8*longSize;
 
// Returns true if binary representations of
// a and b are anagram.
static boolean bit_anagram_check(long a)
{
    // _popcnt64(a) gives number of 1's present
    // in binary representation of a. If number
    // of 1s is half of total bits, return true.
    return (Integer.bitCount((int)a) == (ULL_SIZE >> 1));
}
 
// Driver code
public static void main(String[] args)
{
long a = 4294967295L;
    System.out.println(bit_anagram_check(a));
}
}
 
/* This code contributed by PrinciRaj1992 */

Python3

# An efficient Python3 program to check
# if binary representations of a number
# and it's complement are anagram.
ULL_SIZE = 64
 
# Returns true if binary representations of
# a and b are anagram.
def bit_anagram_check(a):
 
    #_popcnt64(a) gives number of 1's present
    # in binary representation of a. If number
    # of 1s is half of total bits, return true.
    return (bin(a).count("1") == (ULL_SIZE >> 1))
 
# Driver Code
a = 4294967295
print(int(bit_anagram_check(a)))
 
# This code is contributed by Mohit Kumar

C#

// An efficient C# program to check
// if binary representations of
// a number and it's complement
// are anagram.
using System;
 
class GFG
{
 
static byte longSize = 8;
static int ULL_SIZE = 8*longSize;
 
// Returns true if binary representations of
// a and b are anagram.
static bool bit_anagram_check(long a)
{
    // _popcnt64(a) gives number of 1's present
    // in binary representation of a. If number
    // of 1s is half of total bits, return true.
    return (BitCount((int)a) == (ULL_SIZE >> 1));
}
 
static int BitCount(int n)
{
    int count = 0;
    while (n != 0)
    {
        count++;
        n &= (n - 1);
    }
    return count;
}
 
// Driver code
public static void Main(String[] args)
{
    long a = 4294967295L;
    Console.WriteLine(bit_anagram_check(a));
}
}
 
// This code has been contributed by 29AjayKumar

PHP

<?php
// An efficient PHP program to check
// if binary representations of
// a number and it's complement
// are anagram.
 
// Returns true if binary representations
// of a and b are anagram.
function bit_anagram_check($a)
{
    $longSize = 8;
    $ULL_SIZE = 8 * $longSize;
     
    // _popcnt64(a) gives number of 1's present
    // in binary representation of a. If number
    // of 1s is half of total bits, return true.
    return (BitCount($a) == ($ULL_SIZE >> 1));
}
 
function BitCount($n)
{
    $count = 0;
    while ($n != 0)
    {
        $count++;
        $n &= ($n - 1);
    }
    return $count;
}
 
// Driver code
$a = 4294967295;
echo(bit_anagram_check($a));
 
// This code contributed by Rajput-Ji
?>

Javascript

<script>
 
// An efficient javascript
// program to check if binary
// representations of a number and
// it's complement are anagram.
 
 
var longSize = 8;
var ULL_SIZE = 8*longSize;
 
// Returns true if binary representations of
// a and b are anagram.
function bit_anagram_check(a)
{
    // _popcnt64(a) gives number of 1's present
    // in binary representation of a. If number
    // of 1s is half of total bits, return true.
    var ans =a.toString(2).split('0').join('').length
    == (ULL_SIZE >> 1)?1:0;
    return ans;
}
 
// Driver code
var a = 4294967295;
document.write(bit_anagram_check(a));
 
 
// This code contributed by shikhasingrajput
 
</script>

Producción: 

1

Complejidad de tiempo : O(1)

Espacio auxiliar: O(1)
Nota: 
1. La respuesta solo depende del número, en el enfoque anterior ni siquiera encontramos la necesidad de obtener el complemento del número.
2. El código anterior utiliza funciones específicas de GCC. Si deseamos escribir código para otros compiladores, podemos usar Count set bits en un número entero.
Este artículo es una contribución de Aditya Gupta . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

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