Diferencia absoluta entre el recuento de bits establecidos en N y su reverso

Dado un número entero N , la tarea es encontrar la diferencia absoluta entre el número de bits establecidos presentes en el número N y al revés del número N.

Ejemplos:

Entrada: N = 13
Salida: 2
Explicación:
Representación binaria de (13) 10 = (1101) 2
Recuento de bits establecidos = 3
El reverso de 13 es 31
Representación binaria de (31) 10 = (11111) 2
Recuento de bits establecidos de número invertido = 5
La diferencia absoluta es |3 – 5| =2

Entrada: N = 135
Salida: 0
Explicación: 
Representación binaria de (135) 10 = (10000111) 2
Conteo de bits establecidos =4
El reverso de 135 es 531
Representación binaria de (531) 10 = (1000010011) 2
Conteo de bits establecidos de número invertido = 4
La diferencia absoluta es |4 – 4| = 0

Enfoque: La idea principal es utilizar la función de conjunto de bits de la biblioteca STL .

Siga los pasos a continuación para resolver el problema dado:

  1. Invierta los dígitos del número N y guárdelo en una variable, digamos revN .
  2. Utilice la función de conjunto de bits para contar el número de bits establecidos en N .
  3. Devuelve la diferencia absoluta del número de bits establecidos en N y revN .

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

C++14

// C++ program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the
// reverse number of N
int reverse(int N)
{
    // Stores the
    // reverse of N
    int revn = 0;
 
    // Iterate while N exceeds 0
    while (N > 0) {
        // Extract last digit of N
        int b = N % 10;
 
        // Append the last digit
        // of N to revn
        revn = (revn * 10) + b;
 
        // Remove the last digit of N
        N = N / 10;
    }
 
    return revn;
}
 
// Function to find the absolute difference
// between the set bits in N and its reverse
int findAbsoluteDiffernce(int N)
{
    // Store N as bitset
    bitset<64> a(N);
 
    // Stores the reverse of N
    int revn = reverse(N);
 
    // Stores revn as bitset
    bitset<64> b(revn);
 
    // Count set bits in N
    int setBitsInN = a.count();
 
    // Count set bits in revn
    int setBitsInRevN = b.count();
 
    // Return the absolute difference of
    // set bits in N and its reverse
    return abs(setBitsInN - setBitsInRevN);
}
 
// Driver Code
int main()
{
    // Input
    int N = 13;
 
    // Function call to find absolute
    // difference between the count
    // of set bits in N and its reverse
    cout << findAbsoluteDiffernce(N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the
// reverse number of N
static int reverse(int N)
{
     
    // Stores the
    // reverse of N
    int revn = 0;
 
    // Iterate while N exceeds 0
    while (N > 0)
    {
         
        // Extract last digit of N
        int b = N % 10;
 
        // Append the last digit
        // of N to revn
        revn = (revn * 10) + b;
 
        // Remove the last digit of N
        N = N / 10;
    }
    return revn;
}
 
// Function to find the absolute difference
// between the set bits in N and its reverse
static int findAbsoluteDiffernce(int N)
{
     
    // Count set bits in N
    int setBitsInN = Integer.bitCount(N);
 
    // Stores the reverse of N
    int revn = reverse(N);
 
    // Count set bits in revn
    int setBitsInRevN = Integer.bitCount(revn);
 
    // Return the absolute difference of
    // set bits in N and its reverse
    return Math.abs(setBitsInN - setBitsInRevN);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Input
    int N = 13;
 
    // Function call to find absolute
    // difference between the count
    // of set bits in N and its reverse
    System.out.println(findAbsoluteDiffernce(N));
}
}
 
// This code is contributed by Kingash

Python3

# Python3 program for
# the above approach
 
# Function to find the
# reverse number of N
def reverse(N):
     
    # Stores the
    # reverse of N
    revn = 0
 
    # Iterate while N exceeds 0
    while (N > 0):
         
        # Extract last digit of N
        b = N % 10
 
        # Append the last digit
        # of N to revn
        revn = (revn * 10) + b
 
        # Remove the last digit of N
        N = N // 10
 
    return revn
 
def countSetBits(n):
     
    count = 0
     
    while n:
        count += (n & 1)
        n >>= 1
         
    return count
   
# Function to find the absolute difference
# between the set bits in N and its reverse
def findAbsoluteDiffernce(N):
     
    # Count set bits in N
    setBitsInN = countSetBits(N)
 
    # Stores the reverse of N
    revn = reverse(N)
 
    # Count set bits in revn
    setBitsInRevN = countSetBits(revn)
 
    # Return the absolute difference of
    # set bits in N and its reverse
    return abs(setBitsInN - setBitsInRevN)
 
# Driver Code
 
# Input
N = 13
 
# Function call to find absolute
# difference between the count
# of set bits in N and its reverse
print(findAbsoluteDiffernce(N))
 
# This code is contributed by rohitsingh07052

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the
// reverse number of N
static int reverse(int N)
{
     
    // Stores the
    // reverse of N
    int revn = 0;
 
    // Iterate while N exceeds 0
    while (N > 0)
    {
         
        // Extract last digit of N
        int b = N % 10;
 
        // Append the last digit
        // of N to revn
        revn = (revn * 10) + b;
 
        // Remove the last digit of N
        N = N / 10;
    }
    return revn;
}
 
// Function to get no of set
// bits in binary representation
// of positive integer n
static int countSetBits(int n)
{
    int count = 0;
     
    while (n > 0)
    {
        count += n & 1;
        n >>= 1;
    }
    return count;
}
 
// Function to find the absolute difference
// between the set bits in N and its reverse
static int findAbsoluteDiffernce(int N)
{
     
    // Count set bits in N
    int setBitsInN = countSetBits(N);
 
    // Stores the reverse of N
    int revn = reverse(N);
 
    // Count set bits in revn
    int setBitsInRevN = countSetBits(revn);
 
    // Return the absolute difference of
    // set bits in N and its reverse
    return Math.Abs(setBitsInN - setBitsInRevN);
}
 
// Driver Code
public static void Main(string[] args)
{
     
    // Input
    int N = 13;
 
    // Function call to find absolute
    // difference between the count
    // of set bits in N and its reverse
    Console.WriteLine(findAbsoluteDiffernce(N));
}
}
 
// This code is contributed by AnkThon

Javascript

<script>
 
        // Javascript program for the
        // above approach
 
        // Function to find the
        // reverse number of N
        function reverse( n ) {
        // converting the number to String
            n = n + "";
 
       // splitting the digits into an array
            let arr = n.split("")
 
      // reversing the array
            let revn = arr.reverse()
 
            //joining all in a single string
            return revn.join("");
        }
 
        // Function to find
        // the absolute difference
        // between the set bits in N
        // and its reverse
        function findAbsoluteDiffernce(N) {
 
            // Count set bits in N
            let setBitsInN =
            N.toString(2).split('1').length - 1
             
            // Stores the reverse of N
            let revn = reverse(N);
             
            // Count set bits in revn
            let setBitsInRevN =
            revn.toString(2).split('1').length - 1
             
            // Return the absolute difference of
            // set bits in N and its reverse
            return Math.abs(setBitsInN - setBitsInRevN);
        }
 
        // Driver Code
 
        // Input
        let N = 13;
 
        // Function call to find absolute
        // difference between the count
        // of set bits in N and its reverse
        document.write(findAbsoluteDiffernce(N))
 
        // This code is contributed by Hritik
         
    </script>
Producción: 

2

 

Complejidad temporal: O(log N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

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