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