给定两个整数x和y ,任务是使用位运算找到这些数字的平均值,即(x + y)/ 2 。请注意,此方法将得出结果作为计算平均值的下限值。
例子:
Input: x = 2, y = 4
Output: 3
(2 + 4) / 2 = 3
Input: x = 10, y = 9
Output: 9
方法:可以使用位运算来计算两个数字x和y的平均值:
(x & y) + ((x ^ y) >> 1)
其中&是按位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
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。