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.
Input: x = 2, y = 4
(2 + 4) / 2 = 3
Input: x = 10, y = 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:
- Find the average of first N natural numbers
- Average of first n even natural numbers
- Average of first n odd naturals numbers
- Average of a stream of numbers
- Fast average of two numbers without division
- Compute average of two numbers without overflow
- Average of odd numbers till a given odd number
- Average of Squares of Natural Numbers
- Average of even numbers till a given even number
- Count of numbers which can be made power of 2 by given operation
- Find the subarray with least average
- Program to find simple moving average
- Find the deleted value from the array when average of original elements is given
- Find the index which is the last to be reduced to zero after performing a given operation
- Find letter's position in Alphabet using Bit operation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.