Dados dos enteros x e y , la tarea es encontrar el promedio de estos números, es decir (x + y)/2 usando operaciones de bits. Tenga en cuenta que este método dará como resultado un valor mínimo del promedio calculado.
Ejemplos:
Entrada: x = 2, y = 4
Salida: 3
(2 + 4) / 2 = 3
Entrada: x = 10, y = 9
Salida: 9
Enfoque: el promedio de dos números x e y se puede calcular usando operaciones de bits como:
(x e y) + ((x ^ y) >> 1)
donde & es AND bit a bit, ^ es XOR bit a bit y >> 1 es desplazamiento a la derecha de 1 bit.
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 average // of x and y using bit operations int getAverage(int x, int y) { // Calculate the average // Floor value of (x + y) / 2 int avg = (x & y) + ((x ^ y) >> 1); return avg; } // Driver code int main() { int x = 10, y = 9; cout << getAverage(x, y); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the average // of x and y using bit operations static int getAverage(int x, int y) { // Calculate the average // Floor value of (x + y) / 2 int avg = (x & y) + ((x ^ y) >> 1); return avg; } // Driver code public static void main(String[] args) { int x = 10, y = 9; System.out.print(getAverage(x, y)); } }
Python
# Python 3 implementation of the approach # Function to return the average # of x and y using bit operations def getAverage(x, y): # Calculate the average # Floor value of (x + y) / 2 avg = (x & y) + ((x ^ y) >> 1); return avg # Driver code x = 10 y = 9 print(getAverage(x, y))
C#
// C# implementation of the approach using System; class GFG { // Function to return the average // of x and y using bit operations static int getAverage(int x, int y) { // Calculate the average // Floor value of (x + y) / 2 int avg = (x & y) + ((x ^ y) >> 1); return avg; } // Driver code public static void Main() { int x = 10, y = 9; Console.WriteLine(getAverage(x, y)); } } // This code is contributed by AnkitRai01
PHP
<?php // PHP implementation of the approach // Function to return the average // of x and y using bit operations function getAverage($x, $y) { // Calculate the average // Floor value of (x + y) / 2 $avg = ($x & $y) + (($x ^ $y) >> 1); return $avg; } // Driver code $x = 10; $y = 9; echo getAverage($x, $y); // This code is contributed by ajit. ?>
Javascript
<script> // javascript implementation of the approach // Function to return the average // of x and y using bit operations function getAverage(x , y) { // Calculate the average // Floor value of (x + y) / 2 var avg = (x & y) + ((x ^ y) >> 1); return avg; } // Driver code var x = 10, y = 9; document.write(getAverage(x, y)); // This code is contributed by Rajput-Ji </script>
Producción:
9
Complejidad de tiempo: O(1)
Espacio Auxiliar: O(1)