Find average of two numbers using bit operation
Last Updated :
30 May, 2022
Given two integers x and y, the task is to find the average of these numbers i.e. (x + y) / 2 using bit operations. Note that this method will give result as floor value of the calculated average.
Examples:
Input: x = 2, y = 4
Output: 3
(2 + 4) / 2 = 3
Input: x = 10, y = 9
Output: 9
Approach: Average of two numbers x and y can be calculated using bit operations as:
(x & y) + ((x ^ y) >> 1)
where & is bitwise AND, ^ is bitwise XOR and >> 1 is right shift by 1 bit.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getAverage( int x, int y)
{
int avg = (x & y) + ((x ^ y) >> 1);
return avg;
}
int main()
{
int x = 10, y = 9;
cout << getAverage(x, y);
return 0;
}
|
Java
class GFG {
static int getAverage( int x, int y)
{
int avg = (x & y) + ((x ^ y) >> 1 );
return avg;
}
public static void main(String[] args)
{
int x = 10 , y = 9 ;
System.out.print(getAverage(x, y));
}
}
|
Python
def getAverage(x, y):
avg = (x & y) + ((x ^ y) >> 1 );
return avg
x = 10
y = 9
print (getAverage(x, y))
|
C#
using System;
class GFG
{
static int getAverage( int x, int y)
{
int avg = (x & y) + ((x ^ y) >> 1);
return avg;
}
public static void Main()
{
int x = 10, y = 9;
Console.WriteLine(getAverage(x, y));
}
}
|
PHP
<?php
function getAverage( $x , $y )
{
$avg = ( $x & $y ) + (( $x ^ $y ) >> 1);
return $avg ;
}
$x = 10;
$y = 9;
echo getAverage( $x , $y );
?>
|
Javascript
<script>
function getAverage(x , y)
{
var avg = (x & y) + ((x ^ y) >> 1);
return avg;
}
var x = 10, y = 9;
document.write(getAverage(x, y));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...