Alternar todos los bits pares de un número

Dado un número, la tarea es alternar todos los bits pares de un número
. Ejemplos: 
 

Input : 10
Output : 0
binary representation 1 0 1 0
after toggle          0 0 0 0 


Input : 20
Output : 30
binary representation 1 0 1 0 0
after toggle          1 1 1 1 0

1. Primero genere un número que contenga bits de posición pares. 
2. Tome XOR con el número original. Tenga en cuenta que 1 ^ 1 = 0 y 1 ^ 0 = 1.
Comprendamos este enfoque con el siguiente código. 
 

C++

// CPP code to Toggle all even
// bit of a number
#include <iostream>
using namespace std;
 
// Returns a number which has all even
// bits of n toggled.
int evenbittogglenumber(int n)
{
    // Generate number form of 101010
    // ..till of same order as n
    int res = 0, count = 0;
    for (int temp = n; temp > 0; temp >>= 1) {
 
        // if bit is even then generate
        // number and or with res
        if (count % 2 == 1)
            res |= (1 << count);     
 
        count++;
    }
 
    // return toggled number
    return n ^ res;
}
 
// Driver code
int main()
{
    int n = 11;
    cout << evenbittogglenumber(n);
    return 0;
}

Java

// Java code to Toggle all
// even bit of a number
import java.io.*;
 
class GFG {
     
    // Returns a number which has
    // all even bits of n toggled.
    static int evenbittogglenumber(int n)
    {
        // Generate number form of 101010
        // ..till of same order as n
        int res = 0, count = 0;
        for (int temp = n; temp > 0;
                               temp >>= 1)
        {
            // if bit is even then generate
            // number and or with res
            if (count % 2 == 1)
                res |= (1 << count);     
      
            count++;
        }
      
        // return toggled number
        return n ^ res;
    }
      
    // Driver code
    public static void main(String args[])
    {
        int n = 11;
        System.out.println(evenbittogglenumber(n));
    }
}
 
// This code is contributed by Nikita Tiwari.

Python3

# Python code to Toggle all
# even bit of a number
 
# Returns a number which has all even
# bits of n toggled.
def evenbittogglenumber(n) :
 
    # Generate number form of 101010
    # ..till of same order as n
    res = 0
    count = 0
    temp = n
 
    while (temp > 0) :
         
        # if bit is even then generate
        # number and or with res
        if (count % 2 == 1) :
            res = res | (1 << count)    
  
        count = count + 1
        temp >>= 1
         
  
    # return toggled number
    return n ^ res
  
# Driver code
n = 11
print(evenbittogglenumber(n))
 
#This code is contributed by Nikita Tiwari.

C#

// C# code to Toggle all
// even bit of a number
using System;
  
class GFG {
      
    // Returns a number which has
    // all even bits of n toggled.
    static int evenbittogglenumber(int n)
    {
        // Generate number form of 101010
        // ..till of same order as n
        int res = 0, count = 0;
         
        for (int temp = n; temp > 0;
                               temp >>= 1)
        {
            // if bit is even then generate
            // number and or with res
            if (count % 2 == 1)
                res |= (1 << count);     
       
            count++;
        }
       
        // return toggled number
        return n ^ res;
    }
       
    // Driver code
    public static void Main()
    {
         
        int n = 11;
         
        Console.WriteLine(evenbittogglenumber(n));
    }
}
  
// This code is contributed by Anant Agarwal.

PHP

<?php
// php code to Toggle all
// even bit of a number
 
// Returns a number which has
// all even bits of n toggled.
function evenbittogglenumber($n)
{
     
    // Generate number form of 101010
    // ..till of same order as n
    $res = 0;
    $count = 0;
    for ($temp = $n; $temp > 0; $temp >>= 1)
    {
 
        // if bit is even then generate
        // number and or with res
        if ($count % 2 == 1)
            $res |= (1 << $count);    
 
        $count++;
    }
 
    // return toggled number
    return $n ^ $res;
}
 
    // Driver code
    $n = 11;
    echo evenbittogglenumber($n);
 
// This code is contributed by mits
?>

Javascript

<script>
 
// JavaScript program to Toggle all
// even bit of a number
 
    // Returns a number which has
    // all even bits of n toggled.
    function evenbittogglenumber(n)
    {
        // Generate number form of 101010
        // ..till of same order as n
        let res = 0, count = 0;
           
        for (let temp = n; temp > 0;
                               temp >>= 1)
        {
            // if bit is even then generate
            // number and or with res
            if (count % 2 == 1)
                res |= (1 << count);     
         
            count++;
        }
         
        // return toggled number
        return n ^ res;
    }
 
 
// Driver code
 
    let n = 11;
           
        document.write(evenbittogglenumber(n));
 
</script>
Producción

1

Complejidad de tiempo: O (log n)

Espacio Auxiliar: O(1)

Otro enfoque:

Para cambiar un poco, podemos tomar XOR de 1 y ese bit (como 1 ^ 1 = 0 y 1 ^ 0 = 1). Por lo tanto, para establecer todos los bits impares de un número de n bits, necesitamos usar una máscara de bits que es un número binario de n bits con todos los bits impares establecidos. Esta máscara se puede generar en 1 paso usando la fórmula de la suma de una progresión geométrica, como un número de n bits … 1010 es igual a 2 1 + 2 3 + 2 5 + …. 2 (n – !(n % 1)) .

C++

//C++ implementation of the approach
 
#include <bits/stdc++.h>
using namespace std;
 
//function to toggle all the even bits
long long int evenbittogglenumber(long long int n) {
    //calculating number of bits using log
    int numOfBits = 1 + (int)log2(n);
      //if there is only one bit,
      if (numOfBits == 1)
          return n;
    //calculating the max power of GP series
    int m = (numOfBits / 2);
    //calculating mask using GP sum
      //which is a(r ^ n - 1) / (r - 1)
      //where a = 2, r = 4, n = m
    int mask = 2 * (pow(4, m) - 1) / 3;
    //toggling all even bits using mask ^ n
    return mask ^ n;
    }
 
// Driver code
int main()
{
    int n = 11;
    //function call
    cout << evenbittogglenumber(n);
    return 0;
}
 
//this code is contributed by phasing17

C#

// C# implementation of the approach
using System;
 
class GFG {
 
  // function to toggle all the even bits
  static int evenbittogglenumber(int n)
  {
 
    // calculating number of bits using log
    int numOfBits
      = 1 + (int)(Math.Log(n) / Math.Log(2));
 
    // if there is only one bit,
    if (numOfBits == 1)
      return n;
 
    // calculating the max power of GP series
    int m = (numOfBits / 2);
 
    // calculating mask using GP sum
    // which is a(r ^ n - 1) / (r - 1)
    // where a = 2, r = 4, n = m
    int mask = 2 * (int)(Math.Pow(4, m) - 1) / 3;
 
    // toggling all even bits using mask ^ n
    return mask ^ n;
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int n = 11;
 
    // Function call
    Console.WriteLine(evenbittogglenumber(n));
  }
}
 
// This code is contributed by phasing17

Javascript

//JavaScript implementation of the approach
 
 
//function to toggle all the even bits
function evenbittogglenumber(n) {
     
    //calculating number of bits using log
    let numOfBits = 1 + Math.floor(Math.log2(n));
     
      //if there is only one bit,
      if (numOfBits == 1)
          return n;
           
    //calculating the max power of GP series
    let m = Math.floor(numOfBits / 2);
     
    //calculating mask using GP sum
      //which is a(r ^ n - 1) / (r - 1)
      //where a = 2, r = 4, n = m
    let mask = Math.floor(2 * (Math.pow(4, m) - 1) / 3);
     
    //toggling all even bits using mask ^ n
    return mask ^ n;
    }
 
 
// Driver code
let n = 11;
     
//function call
console.log(evenbittogglenumber(n));
 
 
//this code is contributed by phasing17
Producción

1

Tiempo Complejidad : O(1)

Espacio Auxiliar : O(1)

Publicación traducida automáticamente

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