📜  使用位运算查找两个数字的平均值

📅  最后修改于: 2021-04-29 18:51:22             🧑  作者: Mango

给定两个整数xy ,任务是使用位运算找到这些数字的平均值,即(x + y)/ 2请注意,此方法将得出结果,作为计算出的平均值的底值。
例子:

方法:可以使用位运算来计算两个数字xy的平均值:

其中是按位AND, ^是按位XOR, >> 1右移1位。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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
> 1);
 
    return $avg;
}
 
// Driver code
    $x = 10;
    $y = 9;
 
    echo getAverage($x, $y);
 
// This code is contributed by ajit.
?>


Javascript


输出:
9