Find the average of two integers

Source: Internet
Author: User

Find two integer averages, simple! Is it simple?

Entry level: Add, divide

Simple!

int getaverage (intint  input2) {    int average = (input1 + input2)/2  ;     return average;}

Such a method of averaging to do college programming problem is basically enough, but, is not beautiful enough!

Into the class: Plus, bit

We know that 2 of exponential multiplication and subtraction is essentially a shift operation, so we can try to change the 2 to the right by 1 bits, so there are:

int getaverage (intint  input2) {    int average = (input1 + input2) > > 1;     return average;}

With the upper operation of the moment to feel the force lattice high have no, haha, but don't be happy too early, this method handles "normal" int number is no problem, but when the value of Input1+input2 overflow (<integer.min_value or >integer.max_ VALUE), but if we can make sure that input is always negative (such as array subscript), we can use the unsigned Right shift (>>>) instead of the signed right Shift (>>), and this avoids the problem of input and overflow. Because the unsigned right shift will only fill 0 on the left slot. To sum up, when you determine that input must be non-negative, we have the following strong implementations:

int getaverage (intint  input2) {    int average = (input1 + input2) > >> 1;     return average;}
Advanced: bit, plus

Here you might ask, isn't there a perfect way to solve the problem of input and negative or overflow? The answer is, there! Please see:

int getaverage (intint  input2) {    int average = (input1 & Input2) + ((input1 ^ input2) >> 1);     return average;}

As you can see, the computational formula becomes more complex, but the robustness is improved!

Average number of two integers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.